Python program to print terms of Fibonacci Series Using for Loop

This Python Fibonacci series program allows the user to enter any positive integer and displays the terms of Fibonacci series using Python for Loop.

Fibonacci Series starts 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms.

First term = 0

Second term = 1

Third term = first term + Second term

Third term will be obtained by adding first two terms. Hence; third term will be 0 + 1 = 1.

Fourth term will be obtained by adding second and third term; Hence fourth term will be 1 + 1 = 2

Fifth term will be obtained by adding third and fourth term ; Hence Fifth term will be 1 + 2 = 3

Sixth term will be obtained by adding fourth term and fifth term ; Hence Sixth term will be 2 + 3 = 5 and so on.

Below is source code of Fibonacci series

#Display the terms of Fibonacci Series

# first two terms
n1 = 0
n2 = 1
term = int(input("Enter the number of terms : "))
# if number is negative or zero 
if term <=0:
    print("Please enter positive number only")
else:
# if there is only one term entered by user
    if term ==1:
        print(n1,end = " ")
    else :
        print(n1,n2,end=" ")
        for i in range(2,term):
            n3 = n1+n2
            print(n3,end=" ")
            n1 = n2
            n2 = n3

Output:

>>> %Run fibonacci.py
Enter the number of terms : 10
0 1 1 2 3 5 8 13 21 34 
>>> %Run fibonacci.py
Enter the number of terms : 20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Program Description

In this program , we declared two integer variables n1 and n2 as first two terms and assign 0 and 1 respectively.This Python Fibonacci series program allows the user to enter any positive integer and then, that number assigned to variable Number.

We used if statement to check whether user had entered positive number or not. If user had entered positive number then it will print first two terms and then we used for loop which start from 2 to user specified number. Next, new term will be obtained by adding preceding two term

Below is Snapshot of Fibonacci Series with output

Python Fibonacci Series Program using For loop

Python programs:

<

Leave a Reply

Your email address will not be published.