0

I've tried to generate the fibonacci in python but I've noticed that if I do it with swapping it gives me a different value than if I was to do it with simple assignment

def fib_num(max):
    a = 0
    b = 1
    for i in range(max):
         # a,b = b+a,a  this way it is right

         # but if I will implement it like below with simple assigment,
         # I am not going to get the same result Why???
         a  = b+a  
         b = a

         yield a
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
J.Doe
  • 35
  • 1
  • 4

1 Answers1

2

Multiple assignment is implicitly creating a temp variable for you. Your code is assigning a new value to a, and when you use it again it'll have the new value, not the old one:

a = b + a  
b = a

The correct, equivalent solution would be:

temp = a
a = b + a  
b = temp
Óscar López
  • 232,561
  • 37
  • 312
  • 386