-2

This does not print the correct Fibonacci series i.e. 1 1 2 3 5 8...

print ('Fibonacci series...')
 a,b = 0,1
 while b<50:
  print(b)
  a = b
  b = a + b

Please let me know if there is a better way to do this.

Sushrut Kanetkar
  • 363
  • 3
  • 13

2 Answers2

4

Firstly, there is an indentation error in the first code snippet. The last two lines should be indented so they are executed within the while loop.

print ('Fibonacci series...')
a,b = 0,1
while b<50:
 print(b)
 a = b
 b = a+b

However, this still won't produce the correct result. Let's look at why these two code snippets are different.

  1. a, b = b, a + b: This will assign a to b and b to a + b, with the evaluation of the right-hand side before the left-hand side. This means before looking at what variables to assign new values to, Python will first see what b and a + b are. This means the old value of a will be used for setting b = a + b. You can read more about this here.

    a = 1
    b = 2
    a, b = b, a + b  # set a to 2, set b to 1 + 2
    print(a)  # 2
    print(b)  # 3
    
  2. a = b; b = a + b: This does assignment sequentially, such that a is first set to b, then used in the assignment calculation.

    a = 1
    b = 2
    a = b  # set a to 2
    b = a + b  # set b to 2 + 2
    print(a)  # 2
    print(b)  # 4
    
Community
  • 1
  • 1
Karin
  • 8,404
  • 25
  • 34
2
a=b
b = a+b

in the first code sample is equivalent to b = b * 2. Instead you want b += original_value(a). So you either need to do tuple assignment, as in the second code sample (a,b = b, a+b), or use a temp variable:

temp = a
a = b
b += temp

to get the desired value changes.

Craig Burgler
  • 1,749
  • 10
  • 19