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
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
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 12345, 54321 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
Loop starts
a = 0 , b=1 ; b < 10
so a, b = b, a+b is a =1 ,b = 1
now a= 1, b= 1 ; b< 10
so a, b = b, a+b is 1, 2
now a = 1, b = 2; b < 10
so a, b = b, a+b is 2, 3
now a = 2, b = 3; b < 10
so a, b = b, a+b is 3, 5
now a = 3, b = 5; b < 10
so a, b = b, a+b is 5, 8
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