0

I want to calculate the Fibonacci series in Python 3.5 If I do:

a = 0
b = 1
while b < 100:
    print(b)
    a, b = b, a + b 

I get the right result, but if I do:

a = 0
b = 1
while b < 100:
    print(b)
    a = b
    b = a + b

It simply does not work. Why is this?

1
  • 3
    What's a's value after you did a = b? What do you think is the impact in b = a + b? Commented Feb 18, 2016 at 15:18

3 Answers 3

2

When you do this

a = b
b = a + b

then the assignment to a is executed first, and then the assignment to b, but at this time, a already has a new value. In effect, this is the same as

a = b
b = b + b # now a is the same as b

With the "double assignment", the two variables are updated at the same time

a, b = b, a + b 

This assigns the tuple (b, a + b) to the tuple (a, b), using tuple-unpacking to distribute the values to a and b. You could think of this as being roughly equivalent to

temp = b, a + b 
a = temp[0]
b = temp[1]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Now it is clear. I thought that even when they are in the same line. The first variable had priority over the second. But now it is clear that both are updated at the same time.
0

In the first iteration, the value of a changes to 1 which calculates b differently than in the second, where a + b = 2. In the first example, a + b = 1. At least, that's what it looks like to me.

Comments

0

In the first instance, inside the loop during the first run,

a, b = 1, 0+1

Leading a and b to be 1 and 1

In the second instance,

a = 1
b = 1 + 1
Leading a and b to be 1 and 2

The difference is that in the second instance, you're updating the value of b with an already updated value of a. Whereas in the first instance you're updating the value of b using the old value of a.

Comments

Your Answer

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.