0

I was going through an python 3.7 documentation and I saw this example code which I tried out and had the following results.

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
...     print(a)
...     a, b = b, a+b
...
0
1
1
2
3
5
8

I then tried to rewrite the code differently hoping to produce the same results. However I tried the following and got a different result. Please what is the difference between this and that above and why are the results different.

>>>a, b = 0, 1
>>>while a < 10:
    print(a)
    a = b
    b = a + b
0
1
2
4
8

1 Answers1

4
a, b = b, a + b

is equivalent to

temp = b, a + b
a = temp[0]
b = temp[1]

Notice that this doesn't perform the assignments to variables in parallel with evaluating the values on the right side of the =. Everything on the right side is evaluated before performing any assignments.

In your version, the calculation a + b is done after assigning a = b. But in order to get the correct answer, you need to use the old value of a in that addition, not the updated value.

If you want to write it sequentially you can do

next_b = a + b
a = b
b = next_b

or

old_a = a
a = b
b = old_a + b
Barmar
  • 741,623
  • 53
  • 500
  • 612