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!
a, b = 0, 1
while b < 10:
print(b)
a, b = b, a+b
a, b = 0, 1
while b < 10:
print(b)
a = b
b = a+b
Multiple assignment in Python: Assign multiple values or the same value to multiple variables. In Python, use the = operator to assign values to variables. You can assign values to multiple variables on one line.
Assign Values to Multiple Variables in One Line Given above is the mechanism for assigning just variables in Python but it is possible to assign multiple variables at the same time. Python assigns values from right to left.
Multiple variable assignment is also known as tuple unpacking or iterable unpacking. It allows us to assign multiple variables at the same time in one single line of code. In the example above, we assigned three string values to three variables in one shot. As the output shows, the assignment works as we expect.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With