Kelvin Ye Kelvin Ye - 1 month ago 17
Python Question

Python multiple variable assignment confusion

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

Answer

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.