In Fibonacci series the first and second terms are 0 and 1. All additional phrases are obtained by combining the two preceding terms. The recurrence relation defines the sequence “Fn” of the Fibonacci sequence of numbers in mathematical terms:
Fn = Fn-1+ Fn-2
Where to find seed values:
F0=0 as well as F1=1
Contents
Fibonacci Using While Loop
# Program to display the Fibonacci sequence
n = int(input("Enter no of the terms to print "))
# Initialize first two terms
t1, t2 = 0, 1
c = 0
if n <= 0:
print("Enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n,":")
print(n1)
else:
print("Fibonacci sequence:")
while c < n:
print(t1)
tn = t1 + t2
t1 = t2
t2 = tn
c += 1
Output:
Enter no of the terms to print 8
Fibonacci sequence:
0
1
1
2
3
5
8
13
Fibonacci Using recursion
def Fibo(num):
if num <= 1:
return num
else:
return(Fibo(num-1) + Fibo(num-2))
n= int(input("Enter no of the terms to print "))
# check if the number of terms is valid
if n <= 0:
print("Enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(n):
print(Fibo(i))
Output:
Enter no of the terms to print 9
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
Also Read:
Factorial of a number in python