I'm quite new to Python and learning it on Lynda.com, which does not seem to have any way to ask questions about lesson content. In a video about while loops there is this code:
a, b = 0, 1
while b < 50:
print(b)
a, b = b, a + b
that results in: 1, 1, 2, 3, 5, 8, 13, 21, 34
. Out of curiosity, I changed the a, b = b, a + b
parallel assignment to two separate simple assignments:
a = b
b = a + b
but that changes the result to: 1, 2, 4, 8, 16, 32
My question is - aside from the format, how are these statements different? Why is the result different?
2 Answers 2
Suppose a
is 3 and b
is 5.
Then:
a, b = b, a + b
will do the same thing as:
a, b = 5, 3 + 5
or:
a, b = 5, 8
i.e. it sets a
to 5 and b
to 8.
When you have two separate statements:
a = b
b = a + b
they run in sequence.
First this runs:
a = b
and now a
is 5.
Then this runs:
b = a + b
and now b
is 5 + 5, or 10. The end result is that a is 5 and b is 10, instead of 8.
a = b
b = a + b
In the above statements, the fact that you're using the modified valued of 'a,' (which is now 'b') in the next line is probably the issue.
a, b = b, a + b
Whereas, in the above statement, the modification is done after assigning the values. And the new value of 'a' doesn't reflect in the 'a + b' part. I assume some sort of temporary variables are created with the current values of a and b. But I don't know Python internal workings.
-
There is a fun xor swapping trick that prevents the need for temp variables (extra registers) but indeed that is a detail you can and should happily ignore until performance becomes a critical issue.candied_orange– candied_orange2016年08月08日 01:43:54 +00:00Commented Aug 8, 2016 at 1:43
Explore related questions
See similar questions with these tags.