Reputation: 27
While printing fibonacci Series
a,b,c=1,1,1
while (c<7):
print(b,end=" ")
a,b,c=b,b+1,c+1
the output is >> 1 2 3 5 8 13
and when I was tracing the code I found the result is >> 1 2 4 8 16 32
this output resulted by declaring the variables in this way
a,b,c=1,1,1
while (c<7):
print(b,end=" ")
a=b
b=a+b
c=c+1
So what is the difference between these two different ways in declaring the variables
Upvotes: 2
Views: 69
Reputation: 97641
This line:
a,b,c=b,a+b,c+1
is equivalent to:
new_a = b
new_b = a + b
new_c = c + 1
a = new_a
b = new_b
c = new_c
Upvotes: 1
Reputation: 123608
The difference is that when you say:
a,b,c=b,b+1,c+1
the rhs of =
is evaluated and then the values are assigned to the variables on the lhs.
This would work ok as long as the assignments do not have a side-effect on the subsequent ones. For example:
a=42
b=7+a
c=b-a
isn't the same as
a, b, c = 42, 7+a, b-a
If a, b, c were all set to 0 then in the first case you'd end up with 42, 49, 7 respectively. Whereas in the second case, you'd get 42, 7, 0
Upvotes: 2
Reputation: 398
What's happening in your first example is called "tuple assignment".
Python first constructs the tuple (b, b+1, c+1)
, and then pairwise assigns each value to its corresponding variable.
it's a more pythonic way for assignment.
Upvotes: 1