1

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?

sakisk
3,3972 gold badges26 silver badges24 bronze badges
asked Aug 7, 2016 at 23:09

2 Answers 2

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.

answered Aug 8, 2016 at 1:38
2
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.

answered Aug 7, 2016 at 23:50
1
  • 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. Commented Aug 8, 2016 at 1:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.