Python Fibonacci Series using for loop

Fibonacci Series is a series of numbers in which each is the sum of the two preceding numbers. The first two numbers of the series are always 0 and 1. In this blog post, we will discuss how to generate the Fibonacci sequence using for loop in Python.

Using For Loop to generate Fibonacci Series

To generate the Fibonacci series using for loop, we will initialize the first two numbers of the series, i.e. 0 and 1. We will then use the for loop to generate the subsequent numbers of the series by adding the previous two numbers. The for loop will run for the number of terms we want to generate in the series.

Here’s the Python code to generate the Fibonacci series using for loop:

# Initializing first two numbers of series
a, b = 0, 1

# Generating Fibonacci series using for loop
for i in range(n):
    print(a)
    a, b = b, a + b

In the above code, we have initialized the first two numbers of the series as ‘a’ and ‘b’. We then used the for loop to generate the subsequent numbers of the series. The loop runs for ‘n’ a number of times, where ‘n’ is the number of terms we want to generate in the series.

Example

Let’s understand the above code with an example. Suppose we want to generate the Fibonacci series for 10 terms. We will first initialize the first two numbers of the series i.e. 0 and 1. We will then use the for loop to generate the subsequent numbers of the series by adding the previous two numbers. The loop will run for 10 times, generating 10 terms of the series.

Here’s the Python code and output for the above example:

# Initializing first two numbers of series
a, b = 0, 1

# Generating Fibonacci series using for loop
for i in range(10):
    print(a)
    a, b = b, a + b

Output:

0
1
1
2
3
5
8
13
21
34

As we can see from the output, the above code has generated the Fibonacci series for ten terms.

Related: Python program to print Fibonacci series using recursion

Conclusion

In this blog post, we have discussed how to generate the Fibonacci series using for loop in Python. The for-loop approach is a simple and efficient way to generate the series. We hope this blog post has helped you understand how to generate the Fibonacci series using for loop in Python.