Fibonacci Series Program in Python
In this lesson: Print Fibonacci series in Python using loop, recursion and generator — code, dry run and output. Copy & run. In Hindi & English.
What is the Fibonacci series
The Fibonacci series is a sequence where each number is the sum of the two before it. It starts 0, 1, then continues 1, 2, 3, 5, 8, 13.... It is a favourite programming exercise and a beautiful pattern found in nature too.
Fibonacci with a loop
n = 8
a, b = 0, 1
for i in range(n):
print(a, end=" ")
a, b = b, a + b
We keep two numbers, a and b. Each round we print a, then update both so they move forward through the sequence.
Dry run
| Step | print a | new a (= b) | new b (= a+b) |
|---|---|---|---|
| 1 | 0 | 1 | 1 |
| 2 | 1 | 1 | 2 |
| 3 | 1 | 2 | 3 |
| 4 | 2 | 3 | 5 |
| 5 | 3 | 5 | 8 |
| It keeps going: 0 1 1 2 3 5 8 13 ... | |||
In Fibonacci each number is the sum of the previous two. The line a, b = b, a+b at once makes a become b and b become a+b. So the series moves forward: 0,1,1,2,3,5,8...
How a, b = b, a+b works
This one line is the heart of the program. Python first works out the whole right side using the current values, then assigns both variables together:
a, b = b, a + b
# right side uses OLD a and b
# then a = old b, b = old a + old b
Because both are updated at once, you do not need a temporary variable to hold the old value — Python handles it for you.
Fibonacci with recursion
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
for i in range(8):
print(fib(i), end=" ")
This mirrors the maths: fib(n) = fib(n-1) + fib(n-2), with base cases fib(0)=0 and fib(1)=1. It is elegant but slow for large n — use the loop for big series.
Common mistakes
- Wrong starting values. Begin with
a, b = 0, 1, or the whole series shifts. - Updating a and b separately. Do
a, b = b, a+bin one line, or the second update uses the new a. - Deep recursion for big n. Plain recursion is very slow — prefer the loop.
- Missing the base case in recursion. Without
if n <= 1, it never stops.
Summary
- Fibonacci: each number is the sum of the previous two, starting 0, 1.
- The loop keeps two numbers and prints them in turn.
a, b = b, a+bupdates both at once — no temp variable.- Recursion mirrors the maths but is slow for large n.
- Use the loop for printing long series.
Next, try the factorial program, or practise Python loops.
Frequently Asked Questions
What is the Fibonacci series?
How does a, b = b, a+b work in Python?
a becomes the old b, and b becomes the old a + b — updating both in one clean line without a temporary variable.