Fibonacci Series: Using recursion

Swati Meher
Python’s Gurus
Published in
2 min readJun 4, 2024

Introduction:

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. It’s a common problem in programming and a great way to understand loops and lists in Python. In this article, we’ll learn how to generate a Fibonacci series using a custom function, a while loop, and the list’s append method.

Problem Statement:

We want to create a function that generates the Fibonacci series up to a given number of elements. The series should be stored in a list and returned by the function. Our approach will be simple and easy to understand, making use of basic Python constructs.

Approach:

To solve this problem, we’ll follow these steps:

  1. Define the Function: We’ll create a function named fibonacci_series that takes an integer n as input. This integer represents the number of elements in the Fibonacci series we want to generate.
  2. Initialize the List: We’ll start by creating a list with the first two Fibonacci numbers, 0 and 1.
  3. Generate the Series: Using a while loop, we’ll generate the remaining Fibonacci numbers by adding the last two numbers in the list and appending the result to the list until it contains n elements.
  4. Return the Result: Finally, we’ll return the list containing the Fibonacci series.

Code Implementation:

Here’s the complete Python code to generate the Fibonacci series:

def fibonacci_series(n):
# Initialize the first two Fibonacci numbers and the list to store the series
fib_series = [0, 1]

# Use a while loop to generate the rest of the series
while len(fib_series) < n:
# Append the sum of the last two elements in the series to the list
fib_series.append(fib_series[-1] + fib_series[-2])

# Return the Fibonacci series
return fib_series[:n]

# Example usage
n = 10 # Length of the Fibonacci series
fib_series = fibonacci_series(n)
print(fib_series)

Conclusion:

Generating a Fibonacci series in Python is a great way to practice using loops and lists. By following the steps outlined in this article, you can easily create a function that generates the Fibonacci series up to any desired length. This method is simple, efficient, and easy to understand, making it a perfect exercise for beginners.

Happy coding ;)

Python’s Gurus🚀

Thank you for being a part of the Python’s Gurus community!

Before you go:

  • Be sure to clap x50 time and follow the writer ️👏️️
  • Follow us: Newsletter
  • Do you aspire to become a Guru too? Submit your best article or draft to reach our audience.

--

--

Swati Meher
Python’s Gurus

Data Analyst | Gadget Lover | Hoping to reach 300 Followers here.