Python Program for n-th Fibonacci number

In this article, you will learn to make a Fibonacci series program in python.

Fibonacci series

A Fibonacci sequences is sequences of 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .....

The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. 

Fn = F(n-1) +F(n-2)


To find the Fibonacci series then we have to follow the following  steps

  1. First, we have to take input of n terms from the users.
  2. We have to set the first number 0 and the second number 1.
  3. Now, we have to check whether the n terms are greater than o or not.
  4. And then, we do the sum of the first and second terms and also print the first term.
  5. Then we set the second term to first and sum to the second term.

Program

# Python Program for n-th Fibonacci number
# first take input from the users of the nth term
nth = int(input("How many terms? "))

# set first = 0 and second =1
first = 0
second = 1
count = 0

# check the number is greater than 0 or not
if nth <= 0:
print("Please enter a positive integer")

# if there is only one term, return first
elif nth == 1:
print("Fibonacci sequence upto",nth,":")
print(first)

# otherwise find the fibonacci series
else:
while count < nth:
print(first)
sum = first + second
# make the second value to first and third value to second
first = second
second = sum
count += 1

# fibonacci series in python - docodehere.com

Output

How many terms? 12 0 1 1 2 3 5 8 13 21 34 55 89
Next Post Previous Post
No Comment
Add Comment
comment url