首页 > Python两种赋值为什么效果不同?

Python两种赋值为什么效果不同?

a = 0
b = 1
while b<10:
    print b
    #a,b=b,a+b
    a = b
    b = a + b

看你的代码,你是想写个fibonacci数列的程序吧,a,b = b, a + b 没有啥问题就是把a拿到b的值,b拿到a+b的值,第二段a = b, 你把b赋值给了a,导致这个时候a和b都是b的值,你再调用b=a+b就等于把b变成双倍的b,正确的写法,你应该把a存在一个temp中

temp = a
a = b
b = temp + b


我来补充点文档。你是从这里看到这段代码的吗?下边有解释,注意我加粗的地方:

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

你拆开之后求值顺序就变了。

【热门文章】
【热门文章】