0

Trying to create a fibonacci sequence up to "n" number, I found that the following code only doubles the last value

def fibon(n):
    
    a=0
    b=1
  
    for i in range(n):

        a=b
        b=a+b
        print(b)

But if done in the same line, it is able to do the correct operation

def fibon(n):
    
    a=0
    b=1
  
    for i in range(n):

        a,b=b,a+b
        print(b)

I 'm just wondering why the second methods works, and whats the diference between the two. Thanks.

1 Answers1

1

They're different because in the second version, you're doing the assignment atomically, using the "old" value of a in the a+b computation. In the first version, you're setting a = b first, so you're effectively setting b = 2*b.

Samwise
  • 68,105
  • 3
  • 30
  • 44