Python Language Question?

Rotwang sg552 at hotmail.co.uk
Sun Feb 27 12:01:52 EST 2011


On 27/02/2011 16:45, Paul Symonds wrote:
> Can someone give and explanation of what is happening with the following:
>
>>>> a,b = 0,1 # this assigns a = 0 and b = 1
>
>>>> while b < 10:
> ... print b
> ... a, b = b, a+b
> ...
> 1
> 1
> 2
> 3
> 5
> 8
>
>
>>>> a=0
>>>> b=1
>>>> while b < 1000:
> ... print b
> ... a = b
> ... b = a+b
> ...
> 1
> 2
> 4
> 8
> 16
> 32
> 64
> 128
> 256
> 512
>
>
> Why is this statement .. a, b = b, a+b
> different to ... a = b
> ... b = a+b

Because in the statement

    a, b = b, a + b

Python evaluates both expressions on the RHS before assigning their 
values to the variables on the LHS, whereas in the statements

    a = b
    b = a + b

Python assigns the RHS of the first statement to the variable a, /then/ 
evaluates the RHS of the second statement; the value of a has already 
been changed by the time the RHS of the second statement gets evaluated. 
So e.g. if a = 0 and b = 1, then the first statement says to let a = 1, 
b = 0 + 1, while the other two statements say to let a = 1, then b = 1 + 
1 (the first "1" being the new value of a).



More information about the Python-list mailing list