Fibonacci Sequence with Python

Learn Python — Beginner-friendly guide with a challenge

Oliver Lövström
Internet of Technology
3 min readJan 31, 2024

--

In this article, we are creating a Python program that generates the Fibonacci sequence. This sequence is a series of numbers where each number is the sum of the two preceding ones.

If you’re new to programming, don’t worry. We’ll walk through each line of code together. If you’re eager to see the full code right away, you can find it at the end of the article or on GitHub.

Photo by Giulia May on Unsplash

Fibonacci Sequence Generator

We start by defining a function called fibonacci. This function takes an integer as input and returns a list of integers representing the Fibonacci sequence up to the specified length.

def fibonacci(length: int) -> list[int]:
"""Generate Fibonacci sequence.

:param length: The length of the Fibonacci sequence.
:return: The Fibonacci sequence of length.
"""
if length <= 0:
return []

if length == 1:
return [0]

sequence = [0, 1]
while len(sequence) < length:
next_number = sequence[-1] + sequence[-2]
sequence.append(next_number)

return sequence

Let’s break it down:

  • if length <= 0: return [] - This line ensures that the function returns an empty list if the user inputs a non-positive length.
  • if length == 1: return [0] - If the length is 1, we return a list containing only the first element of the Fibonacci sequence.
  • sequence = [0, 1] - We initialize the sequence with its first two numbers.
  • The while loop continues to add new elements to the sequence until it reaches the specified length, using the Fibonacci formula, where each new element is the sum of the two preceding ones.

Testing the Function

To verify our function, we’ll test it with an example:

print(fibonacci(10))

Running this script should output the first 10 numbers of the Fibonacci sequence:

$ python fibonacci.py
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Making It Interactive

To make it more engaging, we’ll incorporate Python’s input() function. This allows users to specify the sequence's length in the terminal.

Python Entry Point

We begin by defining the Python Entry Point, conventionally defined like this:

if __name__ == "__main__":
main()

Main Function

Here’s our main function:

def main() -> None:
"""Main function."""
while True:
try:
length = int(input("Enter the length of the Fibonacci sequence: "))
if length < 0:
print("Please enter a non-negative integer.")
else:
break
except ValueError:
print("Please enter a valid integer.")

sequence = fibonacci(length)
print("Fibonacci sequence of length", length, ":", sequence)
  • The try-except block handles invalid inputs, ensuring only integers are accepted. For detailed information, see Python documentation
  • if length < 0 , which ensures the length is non-negative.
  • sequence = fibonacci(length) calls our Fibonacci function.
  • Finally, we print the generated sequence.

Implementation

"""Fibonacci."""

def fibonacci(length: int) -> list[int]:
"""Generate Fibonacci sequence.

:param length: The length of the Fibonacci sequence.
:return: The Fibonacci sequence of length.
"""
if length <= 0:
return []

if length == 1:
return [0]

sequence = [0, 1]
while len(sequence) < length:
next_number = sequence[-1] + sequence[-2]
sequence.append(next_number)

return sequence


def main() -> None:
"""Main function."""
while True:
try:
length = int(input("Enter the length of the Fibonacci sequence: "))
if length < 0:
print("Please enter a non-negative integer.")
else:
break
except ValueError:
print("Please enter a valid integer.")

sequence = fibonacci(length)
print("Fibonacci sequence of length", length, ":", sequence)


if __name__ == "__main__":
main()

Running the Program

To run the program, use the command line:

$ python fibonacci.py
Enter the length of the Fibonacci sequence: 20
Fibonacci sequence of length 20 : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]

Challenge

Now, challenge yourself to visualize the Fibonacci spiral. In the coming article, we will reveal the solution:

Hint: Use Turtle graphics or Matplotlib

Further Reading

If you want to learn more about programming and, specifically, Python and Java, see the following course:

Note: If you use my links to order, I’ll get a small kickback. So, if you’re inclined to order anything, feel free to click above.

--

--