Module 4 · Creating multi-parameter functions · Lesson 4 of 5
Fibonacci numbers
The Fibonacci sequence starts 0, 1, and from then on every number is the sum of the two before it. It shows up everywhere from sunflowers to spirals — and it's a lovely thing to compute.
fib(n) = fib(n-1) + fib(n-2)011235813
To build it you only ever need the last two values. The trick is Python's tuple assignment: a, b = b, a + b slides the pair forward in a single step — the new a is the old b, and the new b is their sum.
Run it yourselfruns in your browser · Python
main.py
Both factorial and Fibonacci have a self-referential feel: n! is n × (n-1)!, and each Fibonacci number is defined in terms of earlier ones. That hints at a whole different way to write them — where a function calls itself. That's recursion, and it's next.