1

I recently started to look at a new guide and chose the [python.org tutorial](https://docs.python.org/2/tutorial/. However, in section 3.2, I cannot understand how this code:

a, b = 0, 1
while b < 10:
    print b
    a, b = b, a+b

gives me output

1
1
2
3
5
8

The guide mentions this:

  • The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

Can anyone simplify this more for me?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Reginsmal
  • 127
  • 9

2 Answers2

4

the first line can be unpacked like this:

a = 0
b = 1

Unfortunately, the last line isn't quite so easy since the values are "unpacked" simultaneously. In that case, you need a temporary variable if you want to write it out sequentially:

old_a = a
a = b
b = old_a + b
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • I think I understand. But why does the code need to be structured as print b a, b = b, b + a? Which section of the code indicates that the process should be repeated? – Reginsmal Oct 28 '14 at 22:05
  • @Reginsmal -- The `while` loop is the section that indicates that the operation gets repeated. – mgilson Oct 28 '14 at 22:06
  • So [a, b=b, a+b] is the process that needs to be repeated while only b is printed? Also the value old_a will always be equal to 0? – Reginsmal Oct 28 '14 at 22:08
1

demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place

Means it implement the second expression first (a+b), then equalize a with unmodified b, and b with a+b.

It could looks like that

step1 => a + b
step2 => a = b
         b = step1


            step2       step1     b
loop    |            |        |  
        |            |        | 
        |  a     b   |   mod  |  output
1       |  0     1   |    -   |   >> 1
2       |  1     1   |   0+1  |   >> 1
3       |  1     2   |   1+1  |   >> 2      
4       |  2     3   |   1+2  |   >> 3
5       |  3     5   |   2+3  |   >> 5
6       |  5     8   |   3+5  |   >> 8