Python program to print Fibonacci series using while loop


Consider you want to print the Fibonacci series upto terms given by user.

Fibonacci series starts from 0 and 1 and then continued by the addition of the preceding two numbers. For example : 0, 1, 1, 2, 3, 5, 8, 13,....

terms = int(input("Enter how many terms: "))

first, second = 0, 1
i = 0

if terms <= 0:
   print("Invalid input")
   
elif terms == 1:
   print("\nFibonacci series up to",terms,"terms:")
   print(first)
else:
   print("\nFibonacci series up to",terms,"terms:")
   while i < terms:
     print(first)
     next = first + second
     first = second
     second = next
     i +=1

Try yourself here by providing input in the stdin section.

In the above program,

  • Initializing first to 0 and second to 1.
  • we are checking if the input given by user is valid.
  • If the user requested for only 1 term then print 0.
  • Otherwise we are using while loop based on the condition, count(i) should be less than terms given by user.
  • Logic:
     next = first + second
     first = second
     second = next
  • Incrementing count(i) value by 1.

Results

Enter how many terms: 10
Fibonacci series up to 10 terms:
0
1
1
2
3
5
8
13
21
34