Python programs · Numbers
Python program to print the Fibonacci series
In the Fibonacci series each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8 and so on.
Approach
- Start with the first two numbers, 0 and 1.
- Print the current number.
- Move both numbers along by one step and repeat.
The program
n = int(input()) a, b = 0, 1 for _ in range(n): print(a, end=" ") a, b = b, a + b print()
Sample run
Input
10
Output
0 1 1 2 3 5 8 13 21 34
How the code works
The pair a, b = b, a + b moves both numbers along at once: a becomes the old b, and b becomes the old sum. Because Python works out the right-hand side first, no value is lost. end=" " keeps the numbers on one line, and the final print() ends that line.
Try changing it
- Store the numbers in a list instead of printing them.
- Stop when a number passes 100 instead of after n terms.
Common mistakes
- Updating
afirst and then using it to updateb, which uses the wrong value. - Forgetting the final
print(), so the next output continues on the same line.