The Fibonacci sequence starts with 0 and 1, and each next term is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, ....
Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.
View on GitHuba, b = 0, 1
for _ in range(10):
print(a, end=" ")
a, b = b, a + b
Output:
0 1 1 2 3 5 8 13 21 34
Tuple assignment advances both values without needing a temporary variable.
The source tutorial prints 15 Fibonacci elements using a counter. This keeps the same number of terms with simpler variable names.
n = 15
i = 0
a, b = 0, 1
while i < n:
print(a, end=", ")
a, b = b, a + b
i += 1
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,
The same sequence works with a fixed-count for loop.
n = 15
a, b = 0, 1
for i in range(n):
print(a, end=", ")
a, b = b, a + b
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,
Naive recursion matches the mathematical definition but repeats computations exponentially. Keep n small.
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
print([fib(i) for i in range(10)])
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
lru_cache stores earlier results so recursive Fibonacci can run efficiently for moderate n.
from functools import lru_cache
@lru_cache(None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(30))
Output:
832040
The source tutorial uses yield to produce values lazily. This avoids creating a whole list.
def fibonacci(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
print(list(fibonacci(100)))
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
A reusable helper gives a list, suitable for display or further calculations.
def fibonacci_terms(count):
a, b = 0, 1
result = []
for _ in range(count):
result.append(a)
a, b = b, a + b
return result
print(fibonacci_terms(8))
Output:
[0, 1, 1, 2, 3, 5, 8, 13]
input() returns a string. Convert and validate the value before doing arithmetic.Change the number of terms to 0, 1, 8 and 15; compare loop output with cached recursion. Use the companion practice notebook for runnable examples and self-checks.
The convention used here begins with 0, 1.
It repeatedly recalculates the same subproblems.
Use a generator to iterate lazily without storing the full sequence.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.