5

My first day in Python and get confused with a very short example. Hope anyone can provide some explanation about why there is some difference between these several versions. Please!

V1: the output is 1, 1, 2, 3, 5, 8

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

V2: the output is 1, 2, 4, 8

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

1 Answer 1

5

In the first version, the right hand is evaluated first, so b hasn't been incremented when you add it.

To step through the first version for a couple iterations:

1.

a = 0
b = 1
a, b = 1, 1  # b is 1, and a is 0

2.

a = 1
b = 1
a, b = 1, 2  # b is 1 and a is 1

3.

a = 1
b = 2
a, b = 2, 3  # b is 2 and a is 1

In the second version, b is assigned before you add it, so here's how the second version goes:

1.

a = 0
b = 1
a = b  # a is now 1.
b = a + b  # b is now 2, because both a and b are 1.

2.

a = 1
b = 2
a = b  # a is now 2.
b = a + b  # b is now 4, because both a and b are 2.
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot, Morgan. So the priority of the right expression goes firstly, right?
@KelvinYe Exactly.
No problem, glad I could help.

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.