Python Language Question?

P

Paul Symonds

Can someone give and explanation of what is happening with the following:
.... print b
.... a, b = b, a+b
....
1
1
2
3
5
8

.... 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
 
B

Benjamin Kaplan

Can someone give and explanation of what is happening with the following:


...     print b
...     a, b = b, a+b
...
1
1
2
3
5
8



...     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

Python evaluates the entire right side of the assignment, then assigns
it to the left side. So if a=1 and b=2, then
a, b = b, a+b
a,b = 2, 1+2
a,b = 2, 3
a = 2
b = 3

different to ...     a = b
...                             b = a+b
Here, you're evaluating sequentially.
a = b
a = 2
b = a + b
b = 2 + 2
b = 4.
 
R

Rotwang

Can someone give and explanation of what is happening with the following:

... print b
... a, b = b, a+b
...
1
1
2
3
5
8


... 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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top