0
def fibonacci(x):
    a=0
    b=1
    for i in range(x-1):
        b, a = a+b, b
    return b
 x = input ("Give me the number! ")
 print "The",x,". Fibonacci number: "
 print fibonacci (x)

so the code is fully working, but i do not understand, the b,a=a+b,b line, so what is this doing there?:S

lacexd
  • 903
  • 1
  • 7
  • 22

4 Answers4

6

In python, b, a = a + b, b stores an intermediate tuple automatically before assigning the new values to the variables

Breaking down Python's instructions, b, a = a + b, b is executing this disassembly:

  5          17 LOAD_FAST                1 (b)
             20 LOAD_FAST                0 (a)
             23 LOAD_FAST                1 (b)
             26 BINARY_ADD
             27 ROT_TWO
             28 STORE_FAST               0 (a)
             31 STORE_FAST               1 (b)

In a simpler sense, here's the process:

temp_tuple = (a + b, a)
b, a = temp_tuple

This answer copied from part of another answer of mine here: https://stackoverflow.com/a/21585974/3130539

Community
  • 1
  • 1
mhlester
  • 22,781
  • 10
  • 52
  • 75
1

Python supports a few different forms of multiple assignment. In particular,

>>> a = b = c = 1
>>> a
1
>>> b
1
>>> c
1

and

>>> a, b, c, *the_rest = list(range(10))
>>> a
0
>>> b
1
>>> c
2
>>> the_rest
[3, 4, 5, 6, 7, 8, 9]

So what you have is equivalent to:

tmp = b
b = a+b
a = tmp
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
0

Similar to a basic swap idiom, it is basically like doing the following:

tmp = b
b = a + b
a = tmp
2rs2ts
  • 10,662
  • 10
  • 51
  • 95
0

Python separates the right-hand side expression from the left-hand side assignment. First the right-hand side is evaluated, and the result is stored on the stack, and then the left-hand side names are assigned using opcodes that take values from the stack again.

>>> import dis
>>> def foo(a, b):
...     a, b = b, a
... 
>>> dis.dis(foo)
  2           0 LOAD_FAST                1 (b)
              3 LOAD_FAST                0 (a)
              6 ROT_TWO             
              7 STORE_FAST               0 (a)
             10 STORE_FAST               1 (b)
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE        

It works like any other unpacking assignment.

First, a tuple consisting of the values of b and a is created. Then this tuple is unpacked into a and b, effectively swapping them.

>>> a=5
>>> b=6
>>> a,b = b,a
>>> a
6
>>> b
5

Now using this property, Fibonacci Sequence are generated.

Source: https://stackoverflow.com/a/21047622/1112163

Community
  • 1
  • 1
ajknzhol
  • 6,322
  • 13
  • 45
  • 72