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
aholds the current number andbholds the next one.a, b = b, a + bupdates both at the same time. Python calculates the right side first (using the oldaandb), and then stores both results. With two separate lines (a = b, thenb = a + b), the second line would use the newaand give wrong numbers._is a common name for a loop variable that you do not use.print(*terms)prints the items of the list separated by spaces, without the brackets.
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.