1

I'm new to python so I want to ask you a question..

Previously while I was writing a fibonacci function I tryed to replace

a, b = b, a+b

with

a = b
b = a + b

Believing that it was the same thing but I noted that the output is different (and wrong) Shouldn't these two codes do the same thing? Here it is the full code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def main(args):
    fibonacci(1000)
    return 0

def fibonacci(n):
    a, b = 0, 1
    while b < n:
         print b,
         a, b = b, a+b # if I comment this and decomment the two line below it shows me a different output 
        # a = b
        # b = a + b

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))
cs95
  • 379,657
  • 97
  • 704
  • 746
Hoffman
  • 72
  • 1
  • 9
  • 2
    on the first one, the calculation for the new value of `b` is carried out with the old value of `a`. On the second one with the new one. – Ma0 Nov 22 '16 at 16:33
  • This is explained in the Python tutorial itself, [First Steps Towards Programming](https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming) – Olaf Dietsche Nov 22 '16 at 16:35
  • Relevant: http://stackoverflow.com/questions/40405818/why-doesn-t-executing-a-x-x-a-twice-result-in-a-change-of-values – Chris_Rands Nov 22 '16 at 16:36

2 Answers2

3

when you do:

a, b = b, a+b

a will hold the previous value of b and b will hold a+b based on previous value.

But when you do:

a = b
b = a + b

Value of a is updated to b during a=b and hence a+b will have different result as a is now updated.

For example, see simple code to swap two values. It is possible because of the on the fly change in values:

>>> a , b = 5, 10
>>> a, b = b, a
>>> a, b
(10, 5)
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
2

b, a+b is the same as (b, a+b) (a tuple). When you do a, b = b, a+b you implicilty assign the first element to the variable on the left and the second value to the variable on the right.

In your replacement, you changed a's value before calculating b, which didn't happen before.

So, if we assume a = 1 and b = 2, we have:

a, b = (2, 1+2)
>> print(a)
>> 2
>> print(b)
>> 3

In your latter example, we'd have:

a = 2
b = 2 + 2
>> print(a)
>> 2
>> print(b)
>> 4
lucasnadalutti
  • 5,818
  • 1
  • 28
  • 48