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

a = 0
b = 1
while b<10:
    print b
    #a,b=b,a+b
    a = b
    b = a + b
阅读 3.7k
2 个回答

看你的代码,你是想写个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.

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题