In this tutorial we are going to learn how to print Fibonacci series in Python program using iterative method.
In this series number of elements of the series is depends upon the input of users. Program will print n number of elements in a series which is given by the user as a input.
Before moving directly on the writing Fibonacci series in python program, first you should know
What is Fibonacci Series?
A Fibonacci series is a series in which next number is a sum of previous two numbers.
For example : 0, 1, 1, 2, 3, 5, 8 ……
In Fibonacci Series, first number starts with 0 and second is with 1 and then its grow like,
0
1
0 + 1 = 1
1 + 1 = 2
1 + 2 = 3
2 + 3 = 5 and
so on…
How our program will behave?
Suppose if someone gives an input 5 then our program should print first 5 numbers of the series.
Like if someone given 5 as a input then our Fibonacci series which is written in C should print output as,
0, 1, 1, 2, 3
Python Program to Print Fibonacci Series using Iterative methods
n = int(input("please give a number for fibonacci series : "))
first,second=0,1
print("fibonacci series are : ")
for i in range(0, n):
if i<=1:
result=i
else:
result = first + second;
first = second;
second = result;
print(result)
Output:
please give a number for fibonacci series : 5
fibonacci series are :
0
1
1
2
3
Program Explanation
- User Input: The program starts by asking the user to enter the number of terms in the Fibonacci series they want to see.
- Initialize Variables: Two variables,
first
andsecond
, are initialized to 0 and 1, respectively. These are used to store the first two numbers of the Fibonacci series. - Iterate and Compute:
- The program uses a
for
loop to iterate through numbers from 0 to n-1. - If the current index (i) is 0 or 1, it directly assigns
i
toresult
since the first two Fibonacci numbers are 0 and 1 by definition. - For indices greater than 1, it computes the next Fibonacci number by adding the two preceding numbers (
first
andsecond
). The sum is stored inresult
, and the values offirst
andsecond
are updated accordingly.
- The program uses a
- Output: After the loop, the program prints the value of
result
, which by the end of the loop, holds the nth Fibonacci number.