Python program to generate fibonacci series

 Maths has some wonderful sequences of numbers. one among that is Fibonacci series.

The logic behind Fibonacci series is very simple. It starts with two numbers 0,1 as the first and second elements. the next number is the sum of the previous two numbers. Likewise ,it goes on until it reaches the number of the elements in the series.

In python, it has following steps.

  • This Fibonacci series program starts with getting the number of elements for the series. 
  • Next, it assigns the values to the first two numbers. 
  • It checks the number of elements is less than zero. If yes means, the number is a negative value. So, it prints a message that enter a positive number.
  • Else if the number of elements is equal to 1, it print the the first number alone.
  • Else, it starts a loop. It prints the first value.
  • It adds the previous two numbers and store it into third variable.
  • It exchanges the value of  second variable to first variable and  the value of third variable to second variable.
  • The Loop repeats until n value is zero.

The program is given below.

"Fibonacci.py"

#Python program to generate fibonacci series

#Getting the number of elements for fibonacci series

n=int(input("enter the number of elements:"))

#Assigning values to start fibonacci series x to 0 and y to 1

x,y=0,1

#Check whether the given number is less than zero

if n<=0:

 print("Enter a positive number")

#Check whether the given number is equal to one

elif n==1:

 print("fibonacci sequence  is",n)

 print(x)

else:

 print("The Fibonacci sequence is:")

 for i in range(n):

  print(x)

  z=x+y

  x=y;

  y=z;


Execute this program in any command prompt. You will  get the following output.

This is the simple python program to generate fibonacci series.

No comments:

Post a Comment