Python Program To Print Fibonacci Series Using A Loop

python program to print fibnacci series using a loop

In this tutorial, you will learn to write a Python program to print the Fibonacci series using a loop.

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding numbers.

The first two numbers in the series are 0 and 1, and the rest of the series is generated by adding the previous two numbers.

Therefore, the series starts like this:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, …

There are many different ways to print the Fibonacci series.

To understand this program you should have an understanding of the following topics:

  1. Python Recursion
  2. While loop
  3. For Loop

But in this tutorial, you will learn to print this series using for and while loop.

Python Program To Print Fibonacci Series Using For Loop

n = int(input("Enter the number of terms: "))

# initialize the first two terms
a = 0
b = 1

# print the first n terms of the series
for i in range(n):
    print(a, end=' ')
    # calculate the next term by adding the previous two terms
    temp = a
    a = b
    b = b + temp

In this code, we start by getting the value of n from the user.

This value determines how many terms of the Fibonacci series we want to print.

We then initialize the first two terms of the series as a = 0 and b = 1.

We then use a for loop to iterate over the first n terms of the series.

Inside the loop, we print the value of a, which is the current term of the series.

We then update the values of a and b to be the next two terms of the series.

This is calculated by adding the previous two terms.

By printing the values of an inside the loop, we print out the entire series up to the nth term.

Output

Enter the number of terms: 5
0 1 1 2 3

Python Program To Print Fibonacci Series Using While Loop

n = int(input("Enter the number of terms: "))

# initialize the first two terms
a = 0
b = 1

# print the first n terms of the series
i = 0
while i < n:
    print(a, end=' ')
    # calculate the next term by adding the previous two terms
    temp = a
    a = b
    b = b + temp
    #incrementing i
    i += 1

Output

Enter the number of terms: 10
0 1 1 2 3 5 8 13 21 34


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading