Python Program to print fibonacci series


March 15, 2022, Learn eTutorial
1237

What is a Fibonacci series?

Fibonacci series is a sequence of numbers that are the sum of two preceding numbers starting from zero or one.

For example, A Fibonacci series is 0, 1, 1, 2, 3, 5... here we can easily understand that 0+1 is 1 and the next number is 1+1 = 2 and 1+2 =3 then 2+3 = 5 so on. 

Fibonacci number Checking

How to implement the Fibonacci series in python?

To generate a Fibonacci series in python, we have to accept how many numbers the user wants to print and save that in a variable num. First, we hard print the first two numbers, and then we add the first and second numbers to get the third number using a while loop.

Then we update the values of the first and second numbers as second and third numbers. Then find the sum of the second and third numbers to get the fourth number; that while loop continues until we reach the number given by the user. Finally, we print the Fibonacci series using the print function. In this python program, we introduce a while loop for looping until the count is equal to the number.

ALGORITHM

STEP 1: Accept the number of terms needed in the Fibonacci sequence and store it in a variable using int().

STEP 2: Add the values 0 and 1 to two variables n1 and n2, and a count variable with 2 initialized.

STEP 3: Check whether the user input is valid or not using an if condition if it is less than or equal to zero, and print an error statement.

STEP 4: Use an elif to check if the input is 1. If so, then print 0 as the sequence

STEP 5: Else, we have to print the first two numbers 0, 1, which are hardcoded in two variables with an "end=','" to print a, '' after each element.

STEP 6:  Apply a while loop until the count reaches the number.

STEP 7: Add the n1 and n2 to get the next element and print the result as the third number and so on.

STEP 8: Update the values of n1 as n2 and n2 as nth for getting the next element when the loop continues. Update the count as count +1 till we reach the user number.


To generate a Fibonacci series, we need to know about the below python topics. please refer these topics for a better understanding


Refer to this program to generate the Fibonacci series using the recursion Fibonacci series using recursion in Python.

Python Source Code

                                          number = int(input("How many numbers you want? "))  
 
n1 = 0  
n2 = 1  
count = 0  

if number <= 0:  
   print("enter any positive number")  
elif number == 1:  
   print("Fibonacci series:")  
   print(n1)  
else:  
   print("Fibonacci sequence:")  
    
   while count < number:  
       print(n1)
       nth = n1 + n2  
       # update values  
       n1 = n2  
       n2 = nth  
       count += 1  
                                      

OUTPUT

"How many numbers you want? 5

Fibonacci sequence: 

0,1,1,2,3