Reputation: 878
I have started learning python and my first program on fibonacci started giving me some weird answer, I know I am missing conceptually something so need guide from some expert on this. My program looks like this
#! usr/bin/python
a,b = 0, 1
while (b < 50):
print(b)
a = b
b = a + b
output
1
2
4
8
16
32
But When i wrote like this I got correct result
#! usr/bin/python
a,b = 0, 1
while (b < 50):
print(b)
a,b = b, a + b
output:
1
1
2
3
5
8
13
21
34
Guide me pls
Upvotes: 2
Views: 70
Reputation: 882786
a,b = 0,1
a = b # a <- 1
b = a + b # b <- a + b (1 + 1 = 2)
That's two separate operations where the a
in the final line has already been modified before use.
On the other hand:
a,b = b, a + b
is an atomic operation where everything on the right side of =
is the original value.
Hence it's equivalent to:
a,b = 0,1
t = a # t <- 0
a = b # a <- 1
b = t + b # b <- t + b (0 + 1 = 1)
Upvotes: 6