1

I have these two programs what is the difference in assignment of these two values which print different outputs.

>>> a=0
>>> b=1
>>> while b<10:
...     print(b)
...     a=b
...     b=a+b

output: 1 2 4 8 and

>>>a=0
>>> b=1
>>> while b<10:
...     print(b)
...     a, b = b, a+b

output:1 1 2 3 5 8

Thx, Arun

kick07
  • 614
  • 1
  • 8
  • 19
  • Not a duplicate but closely related: https://stackoverflow.com/q/14836228/5647260 -- explains execution step by step. – Andrew Li Jan 07 '18 at 23:14

1 Answers1

2

The order in which a+b is calculated changes.

In the first case, a+b is calculated after a=b is executed.

In the second case, a+b is calculated before any assignment happens.

In general, what happens in Python is that things at the right of = are evaluated before the assignment happens.


If you're curious, you can take a look of what's happening behind the scenes using dis, that will show you the bytecode:

>>> dis.dis('a, b = b, a+b')
  1           0 LOAD_NAME                0 (b)     # Push the value of 'b' on top of the stack
              2 LOAD_NAME                1 (a)     # Push the value of 'a'
              4 LOAD_NAME                0 (b)     # Push the value of 'b'
              6 BINARY_ADD                         # Compute the sum of the last two values on the stack
             # Now the stack contains the value of 'b' and of 'a+b', in this order
              8 ROT_TWO                            # Swap the two values on top of the stack
             # Now the stack contains the value of 'a+b' and of 'b', in this order
             10 STORE_NAME               1 (a)     # Store the value on top of the stack inside 'a'
             12 STORE_NAME               0 (b)     # Store the value on top of the stack inside 'b'
Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69