Python Fibonacci Nth
def / for loopPractice

Return the Nth Fibonacci number

Each term is the sum of the previous two. Use a function with a loop — track two running values, no array needed.

Picture this: each number is the last two added

Start 0, 1. Repeat: next = a+b, then slide the window.

0, 1start
→
next = a+brule
→
slidea,b = b,next
→
nth valuereturn

In easy words: What is this task?

You return the Nth term of a sequence where each number is the sum of the previous two numbers.

Where this is used

Used in recurrence modelling, algorithm practice, growth simulations, and dynamic programming examples.

Theory: iterative Fibonacci

  • Start with a, b = 0, 1 — first two Fibonacci numbers.
  • Each iteration: swap simultaneously a, b = b, a + b.
  • After N swaps, a holds F(N). No array needed — O(1) space.

Real world: growth modelling

Nature uses Fibonacci in flower petal counts, spiral shells, and stock analysis (Fibonacci retracement levels). Algorithmic trading frameworks call fib(n) thousands of times per second.

Fibonacci sequence — highlighted = F(N)

Select N
1def fib(n):
2a, b = 0, 1
3for _ in range(n): a, b = b, a+b
4return a
6

Example Program

1def fib(n):
2a, b = 0, 1
3for _ in range(n): a, b = b, a+b
4print(fib(6))