PythonMastery

Fibonacci series program in Python

Print the first n terms of the Fibonacci series with a for loop, and all Fibonacci numbers below a limit with a while loop.

In the Fibonacci series, each number is the sum of the two numbers before it. It starts 0, 1, and continues 1, 2, 3, 5, 8, 13, ...

The program

python
n = int(input("How many terms? "))

if n <= 0:
    print("Please enter a number greater than 0.")
else:
    a, b = 0, 1
    terms = []
    for _ in range(n):
        terms.append(a)
        a, b = b, a + b
    print(*terms)

Typed in this example: 10. Press Run to type your own.

output
How many terms? 10
0 1 1 2 3 5 8 13 21 34

How it works

Numbers below a limit

When you want every Fibonacci number below a value (instead of a fixed count), a while loop fits better:

python
limit = 100

a, b = 0, 1
while a < limit:
    print(a, end=" ")
    a, b = b, a + b
print()
output
0 1 1 2 3 5 8 13 21 34 55 89 

end=" " makes print() put a space after each number instead of starting a new line. The last print() ends the line.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Variables & Data Types