5 Different Ways to Generate Fibonacci series in Python

Learn basic concepts using the same mathematical series

Sandeep More
Quick Code

--

Photo by Thomas T on Unsplash

The Fibonacci sequence is a series of numbers where each number is the sum of the previous two numbers. So the sequence starts with the numbers 1 and 1, and then each subsequent number is the sum of the previous two.

Below we will see five different ways to generate the Fibonacci series in Python:

Using a loop:

# Function to generate the Fibonacci sequence using a loop
def fibonacci(n):
# Initialize the sequence with the first two numbers
sequence = [1, 1]

# Generate the rest of the sequence
for i in range(2, n):
# Add the previous two numbers to get the next number in the sequence
next_number = sequence[i - 1] + sequence[i - 2]
sequence.append(next_number)

return sequence

# Generate the Fibonacci sequence up to the 10th number
print(fibonacci(10))

The function starts by creating a list called “sequence” that contains the first two numbers of the Fibonacci sequence, which are 1 and 1.

Then, the function uses a loop to generate the rest of the sequence. The loop starts at the second number in the sequence (which is the third number overall) and continues until it reaches the…

--

--

Sandeep More
Quick Code

Tech Enthusiast, Father, Curious, Reader, Learner, Writer, Traveler !!!