0

Basically I'm quite new to Python, but ive written a code for the Fibonacci Sequence and it doesn't work, i've compared it online and its pretty much the same but when i write it slightly differently, it works! - But I have no idea why, can anyone shed some light on why it is behaving this way?

This code has been built and tested in the Python 3.3.2 Shell.

Working Code:

def fib(n):
    a, b = 0, 1
    while b < n:
          print(b)
          a, b = b, b + a

Non-Working Code:

def fib(n):
    a = 0
    b = 1
    while b < n:
        print(b)
        a = b
        b = b + a

I'm completely confused as to why it only works when the variables are grouped together and not when they are separate.

MistUnleashed
  • 309
  • 1
  • 3
  • 15

2 Answers2

4

I believe it's in the line a,b = b,b+a.

The actual executed version does things a bit differently. An expanded form would be:

c = a
a = b
b = b + c

As b is incremented by the initial value of a, not the adjusted value.

Yeraze
  • 3,269
  • 4
  • 28
  • 42
  • But i thought the variables are defined the same so why do they behave differently? – MistUnleashed May 27 '14 at 22:33
  • Like veedrac says below, there's an intermediate step here that isn't obvious. The right side is calculated and stored in temporary space, then finally assigned to the left... – Yeraze May 27 '14 at 22:55
2

To expand on Yeraze's answer, the actual assignment is closer to

# Make the tuple
a_b = (b, b+a)

# Unpack the tuple
a = a_b[0]
b = a_b[1]

so it's more obvious why the values are set and then assigned.

Veedrac
  • 58,273
  • 15
  • 112
  • 169