[Tutor] Fibonacci Series

Rafael Knuth rafael.knuth at gmail.com
Sun Nov 24 11:24:43 CET 2013


Hej there,

I am making a couple wrong assumptions about the program below, but I
do not know where my thinking mistake is. I have some trouble
understanding what exactly happens within this loop here:

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

What I would expect as an outcome of that while loop, is:

>>
1
2
4
8

Here's my (wrong) assumption about that while loop:

1st loop:
Pretty much straight forward, as b = 1 on the first line of code.
>>
1

2nd loop (the output of the 1st loop is "reused" inside the 2nd loop
which is: b = 1):
a = b = 1
b = a + b = 1 + 1 = 2
>>
2

3rd loop:
a = b = 2
b = a + b = 2 + 2 = 4
>>
4

3rd loop:
a = b = 4
b = a + b = 4 + 4 = 8

break.

Instead, that program's correct output is:
>>
1
1
2
3
5
8

I understand what a Fibonacci Series is, but I struggle to understand
what's happening inside that while loop above.

Also, I would assume that an arbitrary integer can be assigned to "a"
on the first line as what really matters (in my understanding) is the
new value assigned to "a" within the loop. This assumption is wrong as
well:

a, b = 999, 1
while b < 10:
    print(b)
    a, b = b, a +b

>>>
1

The while loop breaks after b = 1 is printed out.
... which makes me wonder, because I would expect a = 999 to be
changed to a = b = 1 after the first loop and the program should
execute the 2nd loop in my understanding ...

Can anyone clarify please?
Thank you!

All the best,

Raf


More information about the Tutor mailing list