Fibonacci Series in Python
Print the first N terms of the Fibonacci sequence using a loop.
BeginnerLoop ProgramsExample 7 of 25
fibonacci-series.py
1# Program to print Fibonacci series up to N terms23n = int(input("Enter number of terms: "))45if n <= 0:6 print("Please enter a positive integer.")7else:8 a, b = 0, 19 for _ in range(n):10 print(a)11 a, b = b, a + b
Output
Enter number of terms: 5 0 1 1 2 3
What's going on
We maintain two variables (a, b) representing consecutive Fibonacci numbers and update them each iteration.
After this program
If the idea is still fuzzy, read Day 9: Loops and Iteration in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 loop programs, or see every topic on Python exercises.