0
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?

Aaron
  • 10,133
  • 1
  • 24
  • 40

4 Answers4

1

The below code is like swapping.

a, b = b, a+b  

Its like doing this

temp = a
a = b
b = temp + b
Praveenkumar
  • 2,056
  • 1
  • 9
  • 18
0
a, b = b, a+b

is equivalent to

tmp = a
a = b
b = tmp+b
Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40
0

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
Jab
  • 26,853
  • 21
  • 75
  • 114
0
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.