The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. It starts with 0 and 1 and continues indefinitely. This sequence appears in mathematics, nature, and computer science.
For example:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
In this tutorial, we will write a Python program to generate the Fibonacci sequence using loops and recursion.
What is the Fibonacci Sequence?
The Fibonacci sequence follows this formula:
\[F(n) = F(n – 1) + F(n – 2)\]Where:
- F(0) = 0, F(1) = 1 (Base cases)
- F(2) = 1 + 0 = 1, F(3) = 1 + 1 = 2, F(4) = 2 + 1 = 3, and so on.
Method 1: Using a Loop (Efficient Approach)
# Taking user input n = int(input("Enter the number of terms: ")) # First two terms a, b = 0, 1 if n <= 0: print("Please enter a positive integer.") elif n == 1: print("Fibonacci sequence:", a) else: print("Fibonacci sequence:", a, b, end=" ") for _ in range(2, n): c = a + b print(c, end=" ") a, b = b, c
Output 1
Enter the number of terms: 8 Fibonacci sequence: 0 1 1 2 3 5 8 13
Output 2
Enter the number of terms: 0 Please enter a positive integer.
Method 2: Using Recursion
def fibonacci(n): if n <= 0: return "Invalid input. Enter a positive integer." elif n == 1: return [0] elif n == 2: return [0, 1] else: seq = fibonacci(n - 1) seq.append(seq[-1] + seq[-2]) return seq # Taking user input n = int(input("Enter the number of terms: ")) print("Fibonacci sequence:", fibonacci(n))
How Recursion Works?
Recursion calls the function repeatedly to calculate each Fibonacci number.
For example, calculating fibonacci(5) works as:
fibonacci(5)=[0, 1, 1, 2, 3]
This method is simpler but less efficient for large numbers due to repeated function calls.
Method 3: Using Python’s Generator (Memory Efficient)
def fibonacci_gen(n): a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b # Taking user input n = int(input("Enter the number of terms: ")) print("Fibonacci sequence:", list(fibonacci_gen(n)))
Generators save memory as they generate values on demand instead of storing the entire sequence.