What is the difference between `a, b = b, a+b` and `a = b; b = a+b` for fibonacci [duplicate]

自作多情 提交于 2019-11-28 14:32:53

when you do:

a, b = b, a+b

a will hold the previous value of b and b will hold a+b based on previous value.

But when you do:

a = b
b = a + b

Value of a is updated to b during a=b and hence a+b will have different result as a is now updated.

For example, see simple code to swap two values. It is possible because of the on the fly change in values:

>>> a , b = 5, 10
>>> a, b = b, a
>>> a, b
(10, 5)

b, a+b is the same as (b, a+b) (a tuple). When you do a, b = b, a+b you implicilty assign the first element to the variable on the left and the second value to the variable on the right.

In your replacement, you changed a's value before calculating b, which didn't happen before.

So, if we assume a = 1 and b = 2, we have:

a, b = (2, 1+2)
>> print(a)
>> 2
>> print(b)
>> 3

In your latter example, we'd have:

a = 2
b = 2 + 2
>> print(a)
>> 2
>> print(b)
>> 4
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!