-1

I'm trying an ultra simple novice exercise. The objective of the exercise was to create a fibonacci pattern, I tried two methods that I thought were going to give the same result. But fires some reason they don't, I can't understand why.

Any ideas?

CODE 1

a = 0
b = 1

while b < 100: 
    print(b)
    a = b
    b = a + b

CODE 2:

a, b = 0, 1

while b < 100:
    print(b)
    a, b = b, a + b
Abe Gold
  • 35
  • 6
  • Check this, I think it will give you the answer https://stackoverflow.com/questions/23085008/python-usage-of-variables-and-their-difference-a-b-0-1-vs-a-0-b – Nick Dec 15 '19 at 00:03

1 Answers1

0

In "CODE 1", a = b makes the next line equivalent to b = b + b, which is not correct.

In "CODE 2", a,b=b,a+b is essentially new_a = old_b; new_b = old_a + old_b. The new values are computed from the old values, then the new values are assigned to the variables. This computes the fibonacci series correctly.

To do it correctly in "CODE 1" a temporary variable is needed:

t = a
a = b
b = t + b # use original a saved in t to compute b

a,b=b,a+b eliminates the need for the temporary variable.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251