Today we’re going to talk about something that might make your eyes glaze over: the Fibonacci series in Python using for loops. But don’t worry, I promise it won’t be as boring as you think. In fact, let me start with a little joke to lighten things up…
Why did the Fibonacci sequence go to college? To get a degree! (I know, groan all you want.)
Okay, now that we got that out of the way, what exactly is the Fibonacci series. It’s a mathematical concept where each number in the sequence is the sum of the two preceding ones, starting with 0 and 1. So it goes like this:
0, 1, 1, 2, 3, 5, 8, 13, 21… and so on. Pretty simple, right? But how do we get those numbers in Python using for loops? Well, let’s take a look at some code:
# This script is used to generate a Fibonacci sequence using for loops in Python.
# First, we set the number of iterations to 10 (you can change this).
for i in range(0, 10):
# We handle the base cases where F(0) = 0 and F(1) = 1.
if i == 0 or i == 1:
print(i) # Output the base cases.
else:
# For all other cases, we use recursion to calculate the next number in the sequence.
# We initialize the previous and current numbers to 0 and 1 respectively.
fib_prev, fib_curr = 0, 1
# We use a for loop with 2 iterations to calculate the next number.
for j in range(2):
if j == 0:
# For the first iteration, we add the previous and current numbers to get the next number.
next_fib = fib_prev + fib_curr
elif j == 1:
# For the second iteration, we output the result of the calculation.
print(next_fib)
# We break out of the loop since we only need to calculate one number.
break
else:
# If there are more than 2 iterations, something went wrong and we raise an error.
raise ValueError("Something went wrong!")
# After the loop, we update the previous and current numbers for the next iteration.
fib_prev, fib_curr = fib_curr, next_fib
Okay, let’s break this down. First we set up a for loop that will iterate 10 times (you can change the number of iterations to whatever you want). Then we handle the base cases where F(0) and F(1) are defined as 0 and 1 respectively.
Next, we use another nested for loop to calculate each subsequent number in the series using recursion. We keep track of the previous two numbers (fib_prev and fib_curr), and then add them together to get the next number (next_fib). Finally, we output the result of each iteration using a print statement inside our second nested for loop.
A Python program that generates the Fibonacci series using recursion with for loops. It’s not exactly rocket science, but hopefully this tutorial helped clarify some things and made you laugh at least once.