This quick tutorial will show you how to generate the Fibonacci sequence of numbers in Python.
This is a useful example for new coders and those just learning Python as it shows how variables, loops, and arithmetic are used in Python.
What is the Fibonacci Sequence
The Fibonacci sequence is a procession of numbers in which each number is the sum of the preceding two numbers.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
Above, the first 13 numbers in the Fibonacci sequence are listed. As you can see, each number is the sum of the two numbers before it, with the sequence starting at 0.
The Fibonacci sequence is often visualised as a spiral, with the spiral growing larger as the size of the numbers increases.
Why are the Fibonacci Numbers Important?
Fibonacci numbers show up everywhere. They appear frequently in mathematics (and are related to the golden ratio), and even biology – appearing in tree branch and leaf arrangements, and the patterns on pinecones and pineapples. Artists use it in their paintings, composers use it in their music — it’s one of the most famous and most studied mathematical concepts.
In computing, they are frequently used in algorithms for sorting, searching, and organising structured data.
As a concept, they are also a way to demonstrate the features of a programming for beginners – which is why were are here.
Generating the Fibonacci Sequence of Numbers in Python
The below Python code is written for Python 3 and will prompt the user for input, then generate a Fibonacci sequence of the required length:
# Prompt the user for the length of the sequence to generate length = int(input("How many numbers in the Fibonacci sequence to generate? ")) # First two numbers in the sequence first, second = 0, 1 # The current iteration count = 0 # The length of the sequence must be a positive integer - you can't have a list with a negative length if length <= 0: # Warn the user print("Invalid number entered - please enter a positive integer") # Exit the application exit() # Generate Fibonacci sequence - iterate through a code block which generates each number in the sequence until the number of iterations matches the requested length of the sequence print("The first " + str(length) + " numbers in the Fibonacci sequence:") while count < length: # Print the current number in the sequence print(first) # Save the current number current = first + second # Update the position in the sequence first = second second = current count += 1