a, b, n = 0, 1, 500
while a < n:
print(a)
a, b = b, a+b
and
a, b, n = 0, 1, 500
while a < n:
print(a)
a = b
b = a+b
Both give different output.
What is the difference between a, b = b, a+b
and a = b; b = a+b
?
a, b, n = 0, 1, 500
while a < n:
print(a)
a, b = b, a+b
and
a, b, n = 0, 1, 500
while a < n:
print(a)
a = b
b = a+b
Both give different output.
What is the difference between a, b = b, a+b
and a = b; b = a+b
?
The below code is like swapping.
a, b = b, a+b
Its like doing this
temp = a
a = b
b = temp + b
This is not comma separated values. You are doing tuple unpacking.
a, b, n = 0, 1, 500
Is the same as:
a, b, n = (0, 1, 500)
The reason they are different is the first line assigns b
to a
then adds a and b together. It’s essentially the same as:
a = b
b = a+b
a, b, n = 0, 1, 500
while a < n:
print(a)
a = b
b = a+b
In above line of code - after print(a), code value in b variable will be assigned to a first and hence the value of a is updated and the updated value of a is being used in b = a+b
Lets say, a =0, b =1 . So after print(a), value of a will be 1 first and b will have 1+1 =2.
Whereas,
a, b, n = 0, 1, 500
while a < n:
print(a)
a, b = b, a+b
In the above code, after print(a), a and b values are simultaneously assigned. In this case, whatever value of a is printed in print(a) will be used in assigning value for a in further step.
Lets say, a = 0 and b = 1 , after print(a) which will print 0 first, value in a will be 1 and value in b will be 0+1 = 1 because b = a+b will use a =0 and not a =1.