Geek Culture
Published in

Geek Culture

Fibonacci Sequence In Python

Iterative Approach and Recursive Approach to Solve Fibonacci Sequence

Python Tutorial Series

Fibonacci Sequence

0,1,1,2,3,5,8,13,21,...

Iterative Approach To Find the nth Term Of Fibonacci Sequence

def fibonacci(n):
assert n>0
secondLast = 0
Last = 1
if n == 1:
print(secondLast)
elif n == 2:
print(Last)
else:
for i in range(3, n+1):
result = secondLast + Last
secondLast = Last
Last = result
print(result)

fibonacci(8)
fibonacci(7)
fibonacci(4)
13
8
2

Recursive Approach To Find the nth Term Of Fibonacci Sequence

def fibonacci(n):
assert n>0
if n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(8))
print(fibonacci(7))
print(fibonacci(4))
13
8
2

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store