0

I am not able to understand how the last line is able to print the Fibonacci series. It will be a great help, if someone can sequentially explain the code.

   a , b = 0 , 1
    while b < 10:
        print(b, end = ' ')
         a, b = b, a + b
Suel Ahmed
  • 63
  • 5
  • https://stackoverflow.com/questions/21990883/python-a-b-b-a-b Please refer to the explanation on above link. I understood the expression. Thanks everyone for the help. – Suel Ahmed Apr 25 '20 at 13:01

2 Answers2

2
a, b = b, a + b

Is packing a tuple b, a + b and unpacking it on the same line a, b =.

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 1234554321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:
x, y, z = t
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences

mkasp98
  • 164
  • 1
  • 6
  • so...if my understanding is correct. then the aforementioned code is equivalent to a = b & b = a + b. Is my interpretation correct? – Suel Ahmed Apr 25 '20 at 10:34
  • What do you mean by the '&'? – mkasp98 Apr 25 '20 at 10:38
  • & not in coding terms but as in English literature a = b and b = a + b – Suel Ahmed Apr 25 '20 at 10:57
  • You can look like this. But keep in mind that the order of this equations doesn't matter. And it's not the same as typing a = b and then (after new line) b = a + b. Because a would have been already changed when calculating a + b. – mkasp98 Apr 25 '20 at 11:02
1

Loop starts

  1. a = 0 , b=1 ; b < 10

    so a, b = b, a+b is a =1 ,b = 1

  2. now a= 1, b= 1 ; b< 10

    so a, b = b, a+b is 1, 2

  3. now a = 1, b = 2; b < 10

    so a, b = b, a+b is 2, 3

  4. now a = 2, b = 3; b < 10

    so a, b = b, a+b is 3, 5

  5. now a = 3, b = 5; b < 10

    so a, b = b, a+b is 5, 8

  6. now a = 5, b = 8; (b > 10)

    so a, b = b, a+b is 8, 13 ; b>10 (loop breaks)

ans is 1 1 2 3 5 8

Community
  • 1
  • 1
Kalyan Mohanty
  • 95
  • 1
  • 10