Write Python. Understand every error.

Open the editor

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

  1. Start with the first two numbers, 0 and 1.
  2. Print the current number.
  3. 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

Run this program in Py-CRAFT

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

Common mistakes

Learn the ideas

More programs

Share this page: