# Solution to Fibonacci Sequence using functions in Python

Here is the solution to Fibonacci Sequence using functions in Python which is given below:

def FibonacciSeries(n):
if n < 0:
print(“Invalid Input”)
elif n==0:
return 0
elif n==1 or n==2:
return 1
else:
return FibonacciSeries(n-1) + FibonacciSeries(n-2)

number = int(input("Enter range: "))
first_fibonacci_series = [FibonacciSeries(i) for i in range(number)]
print(first_fibonacci_series)

I try to run this code and enter 40 as range. I wait for a while just see the output until I decided to cancel it, so this code is inefficient for large values of `n` due to repeated calculations of the same Fibonacci numbers.

You are right. I used recursion at that time to do Fibonacci Sequence. This time I used Optimization to do Fibonacci Sequence. Here is the optimized code below.

def FibonacciSeries(n):
a = 0
b = 1
if n < 0:
print(“Invalid Input”)
elif n==0:
return 0
elif n==1 or n==2:
return 1
else:
for i in range(1, n):
c = a + b
a = b
b = c
return b

number = int(input("Enter range: "))
first_fibonacci_series = [FibonacciSeries(i) for i in range(number)]
print(first_fibonacci_series)

1 Like