Search code examples
pythonloopspython-3.xiteratoriterable-unpacking

Fibonacci sequence python


I am trying to understand Python, but I still don't get it. I am new to the language, and wants to understand it properly. This is a line from a Fibonacci sequence using loops. Please explain the meaning of this code. I am trying to get the pattern by hand. I got the pattern up to 3, but after 3 I am not getting the answer.

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

Solution

  • a, b = b, a + b
    

    This is known as multiple assignment. It's basically an atomic version of:

    a = b
    b = a + b
    

    By atomic, I mean everything on the right is calculated before pacing it into the variables on the left. So a becomes b and b becomes the old version of a plus b, equivalent to the non-atomic:

    old_a = a
    a = b
    b = old_a + b
    

    So, in terms of what you see:

            a                        b               output
    ================    =========================    ======
    (initial values)        (initial values)
            0                        1                  1
    (becomes prev b)    (becomes sum of prev a,b)
            1                        1                  1
            1                        2                  2
            2                        3                  3
            3                        5                  5
            5                        8                  8
    

    That exact code (along with the explanation of multiple assignment) can be found here in the tutorial.