Python Program to Print Fibonacci series - Codicaly

 

In this post, we are going to write a program to print the Fibonacci series.

General idea :

             In mathematics, the Fibonacci number is a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. Like 0,1,1,2,3,5,8,13,21........... In this sequence, 0 and 1 are default numbers. Then the sum of 0 and 1 is 1.Then the sum of 1 and 1 is 2. Then the sum of 1 and 2 is 3. Then the sum of 2 and 3 is 5. And so on.

Pre-Requisites :

  • Python Basics
  • Iteration ( For loop)

Program :

n=int(input("Enter the number of terms"))
total=0
a=0
b=1
print(a)
print(b)
for i in range(0,n-2):
    total=a+b
    print(total)
    a=b
    b=total













Explanation :



1.First we need to input the number of terms we need to print. Here we are doing that using print.






2.Here in these lines we are initializing the total to 0, a to 0, and b to 1. 'a' is the first element and 'b' is the second element.




3. Here we are printing the first two elements of the Fibonacci series i.e, a (0) and b (1) using the print function.



4.Here we are using for loop to print the Fibonacci sequence. We already printed the first two elements. We need to print the remaining elements. If we need to print n elements. We need to print the remaining n-2 elements. Hence the stop value is n-2. This loop will repeat n-2 times.



5. This statement is written under the for loop ( step 4 ).  Here we are assigning the sum of 'a' and 'b' value to the 'total'. If a is 0 and b is 1, then the total will be 2. If the a is 1 and b is 2 then the total is 3.



6. This statement is also written under the for loop ( step 4 ). Here we are printing the total using the print statement. If the total is 1 , then it will be printed in the output.




7. This statement is also written under the for loop ( step 4). In the Fibonacci series, the successive elements are the sum of the preceding element and that element itself. Hence b becomes a and the total becomes b. This will be changed until the loop ends.


Then the new values of a and b are added and assigned to total and printed. For example, after printing o and 1 ( step 2 ), 1 will be total and it will be printed ( step 5 ). Now new 'a' value is b vale i.e,1.  The new 'b' value is total i.e,1. The new total is 1+1=2 is printed. This will be repeated until the loop ends.

Input / Output :







Comments

Popular posts from this blog

Python - Program to find the given number is a prime or composite number

Python Program To Replace The Elements of List With its Cube