DEV Community

Cover image for Writing the Fibonacci Series in Python
Sayandeep Majumdar
Sayandeep Majumdar

Posted on • Updated on

Writing the Fibonacci Series in Python

Introduction:

Python, with its simplicity and wide range of capabilities, has established itself as a favorite among programming languages. One of the classic problems Python can elegantly solve is generating the Fibonacci series, a sequence where each number is the sum of the two preceding ones. In this blog post, we'll guide you on how to write a Python program that takes user input and generates the Fibonacci series accordingly.

Defining the Problem:

The Fibonacci sequence begins as follows: 0, 1, 1, 2, 3, 5, 8, 13... and so on. Each subsequent number is derived by adding the two previous numbers. Our task is to allow the user to specify the length of the series and then output the Fibonacci sequence of that length.

Creating the Solution:

Let's begin by setting up the Python environment. If you haven't already installed Python on your system, you can download it from the official Python website.

Python Code:

Here's a simple Python script to generate a Fibonacci series based on user input:

def fibonacci(n):
    fib_series = [0, 1]
    while len(fib_series) < n:
        fib_series.append(fib_series[-1] + fib_series[-2])
    return fib_series

n = int(input("Enter the length of the Fibonacci series you want: "))
print(fibonacci(n))

Enter fullscreen mode Exit fullscreen mode

Understanding the Code:

  1. We define a function named fibonacci which accepts one argument 'n'. This 'n' is the length of the Fibonacci series we want to generate.
  2. Inside the function, we create a list fib_series initialized with the first two Fibonacci numbers [0, 1].
  3. We then enter a while loop which continues until the length of fib_series becomes equal to 'n'.
  4. In each iteration, we append the sum of the last two numbers of the fib_series list to the list itself, effectively generating the next number in the Fibonacci series.
  5. The function then returns the generated Fibonacci series.
  6. We ask the user for the length of the Fibonacci series they want, convert it to an integer, and store it in 'n'.
  7. Finally, we call the fibonacci function with 'n' as the argument and print the returned series.

Wrapping Up:

This Python program efficiently generates the Fibonacci sequence to the length specified by the user. By allowing user input, it offers an interactive and engaging way to learn about this fascinating numerical series. Try running the script with different inputs and observe the output - it's a fun way to delve deeper into the world of Python programming!

#developerslab101 #pythonseries

Top comments (0)