Python - Difference between variable value declaration on Fibonacci function

痞子三分冷 提交于 2019-11-28 14:17:32

b, a+b creates a tuple containing those two values. Then a, b = ... unpacks the tuple and assigns its values to the variables. In your code however you overwrite the value of a first, so the second line uses the new value.

a, b = b, a + b

is roughly equal to:

tmp = a
a = b
b = tmp + b

When Python executes

a,b = b, a+b

it evaluates the right-hand side first, then unpacks the tuple and assigns the values to a and b. Notice that a+b on the right-hand side is using the old values for a.

When Python executes

a=b
b=a+b

it evaluates b and assigns its value to a. Then it evaluates a+b and assigns that value to b. Notice now that a+b is using the new value for a.

That syntax simultaneously assigns new values to a and b based on the current values. The reason it's not equivalent is that when you write the two separate statements, the second assignment uses the new value of a instead of the old value of a.

In the first example, a isn't updated to take the value of b until the entire line has been evaluated -- so b is actually a + b.

In you example, you've already set a to b, so the last line (b=a+b) could just as easily be b=b+b.

It's all in the order in which things are evaluated.

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