a,b = 0,1
while b < 50:
print(b)
a = b
b = a+b
outputs:
1
2
4
8
16
32
wheras:
a,b = 0,1
while b < 50:
print(b)
a,b = b, a+b
outputs (correct fibonacci sequence):
1
1
2
3
5
8
13
21
34
Aren't they the same? I mean a,b = b, a+b
is essentially the same as a = b
and b = a+b
written separately -- no?
No, they are not the same.
When you write a,b = b, a+b
, the assignments are done "simultaneously". a,b = b, a+b
is same as (a, b) = (b, a+b)
. So, after
a, b = 5, 8
a=5 and b=8. When Python sees this
(a, b) = (b, a+b)
it first calculates the right side (b, a+b)
which is (8,13)
and then assigns (this tuple) to the left side, to (a,b)
.
When you have: a = b
and then b = a+b
, the two operations are done one after the other. But for every one of them:
a = b
It first calculates the right side b
and then assigns (this value) to the left side, to a
. And again
b = a + b
It first calculates the right side a + b
and then assigns (this value) to the left side, to b
.
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