Fibonacci Series in Python. The Fibonacci Series is an intriguing sequence of numbers that has fascinated mathematicians, scientists, and artists for centuries. This sequence begins with two predefined numbers, typically 0 and 1, and each subsequent number is the sum of two preceding ones. This simple yet profound pattern emerged in various natural phenomena, architectural structures, and art forms, Making it a popular subject of study in diverse fields. In this article, we will see how to generate the Fibonacci Series in Python, one of the most popular and beginner-friendly programming languages.
Table of Contents
Implementing Fibonacci Series in Python
Implementing the Fibonacci Series in Python can be achieved in several ways, but we will focus on two primary methods: Itterative and Recursive.
Iterative Approach for Fibonacci Series
The Iterative approach is straightforward and efficient for generating Fibonacci numbers. Here’s how we can implement the Fibonacci Series in Python using an iterative approach-
def fibonacci_iterative(n):
if n<=0:
print("Incorrect input")
return
a,b = 0,1
if n == 1 :
return a
for i in range (2,n):
c = a+b
a,b = b,c
return b
n = int (input("Enter the term of Fibonacci Series "))
print(fibonacci_iterative(n))
In this approach, We use a for-loop to iterate through the sequence, updating the value of two variables ‘a’ and ‘b’ at each step, which represent the two most recent numbers in the series.
Recursive Approach for Fibonacci Series
The recursive approach, While not as efficient for large ‘n’ due to its exponential time complexity, provides appear example of how mathematical function can be translated directly into the code. Here is a simple recursive function to find the nth Fibonacci number-
def fibonacci_recursive(n):
if n<=0:
print("Incorrect input")
return
if n == 1 :
return 0
elif n == 2:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
n = int (input("Enter the term of Fibonacci Series "))
print(fibonacci_recursive(n))
The recursive method is elegant and closely mirrors the mathematical definition of the Fibonacci Sequence. However, due to its repetitive calculation, it is not optimal for large values of ‘n’.
Happy Coding & Learning
1 thought on “Fibonacci Series in Python”