Book a free demo

Easy ยท ages 10+ ยท lists ยท loops ยท patterns

Fibonacci numbers in Python.

Build the Fibonacci sequence, where each number is the sum of the two before it.

The program

Press Run to see what it prints. Change anything you like, then run it again.

fib = [1, 1]
while len(fib) < 15:
    fib.append(fib[-1] + fib[-2])
print(fib)
ratios = [round(fib[i + 1] / fib[i], 4) for i in range(8, 13)]
print("Ratios:", ratios)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
Ratios: [1.6176, 1.6182, 1.618, 1.6181, 1.618]

How it works

  1. A list holds many values in order. fib[-1] is the last one and fib[-2] is the one before it.
  2. append adds a value to the end. The loop runs until the list has 15 numbers.
  3. The last two lines divide each number by the one before it. The answers get closer and closer to 1.618..., the golden ratio. A list comprehension builds a new list in one line.
See the Python path โ†’

Try this

  • Make a list of 30 numbers.
  • Print only the even Fibonacci numbers.
  • Start with different numbers, such as [2, 1], and see what changes.

Stuck on an error? Read how to debug Python.

Similar ideas

More programs

All programs โ†’

FAQ

Fibonacci numbers: questions

What does the fibonacci numbers program do?

Build the Fibonacci sequence, where each number is the sum of the two before it. It prints: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] / Ratios: [1.6176, 1.6182, 1.618, 1.6181, 1.618]

Which Python ideas does it use?

lists, loops, patterns. Easy level, suitable from about age 10.

How do I run it?

Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.

What should I try next?

Make a list of 30 numbers. Print only the even Fibonacci numbers. Start with different numbers, such as [2, 1], and see what changes.

Start a conversation

Want a teacher to guide the learning?

Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.

  • Tell us the learnerโ€™s age or grade and goals
  • Weโ€™ll suggest a suitable class or learning path
  • Weโ€™ll confirm format, timing and fees with a parent or guardian

For a childโ€™s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

Weโ€™ll use your details only to respond to this request.

Play it, don't just read it

Write some code right now

Free games that need no sign-up. Pick one and play for five minutes.

All free games โ†’
Chat on WhatsApp
Esc

Try