How does the fourth line in the code below work?
a, b = 0, 1
while b < 10:
print b
a, b = b, a + b
I don't have a problem, I just don't know how it's working.
How does the fourth line in the code below work?
a, b = 0, 1
while b < 10:
print b
a, b = b, a + b
I don't have a problem, I just don't know how it's working.
If I understand you correctly, you want to explain this line (formatted for readability):
a, b = b, a + b
.
Essentially you are assigning a tuple to another tuple, and when you do that in python you 'unpack' one tuple into the other. You can read about it here.
In your specific case, firstly the tuple (b, a + b)
is evaluated and then it is assigned to the tuple (a, b)
. For example in the first iteration of the loop a = 0
and b = 1
, so (b, a + b) = (1, 1)
. Therefore the last line will be equivalent to (a, b) = (1, 1)
.
You can read more in this question.