Python - Difference between variable value declaration on Fibonacci function

南笙酒味 提交于 2019-11-27 08:11:53

问题


I'm kind of beginner in python. I was looking at one the types to make a fibonacci function,

def fib(n):
a=0
b=1
while a<n:
    print a
    a,b=b,a+b

and I saw the a,b=b,a+b declaration. So, I thought a=b and b=a+b were the same to a,b=a,b+a, so I changed the function for it to be like this:

def fib(n):
a=0
b=1
while a<n:
    print a
    a=b
    b=a+b

and I thought it would be right, but when I executed the program, I got a different output. Can someone explain to me the difference between those two types of declaration?

Thanks, anyway.


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/13351921/python-difference-between-variable-value-declaration-on-fibonacci-function

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