Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function for Fibonacci - Python Program

Example 1 :

def fibonacci(n): """Return n-th Fibonacci number using recursion.""" if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2) print([fibonacci(i) for i in range(7)])

Output

 
OUTPUT  :
[0, 1, 1, 2, 3, 5, 8]
 

Example 2 : Advanced Program

def fibonacci_recursive(n): """ Calculates the nth Fibonacci number recursively. Args: n: The index of the Fibonacci number to calculate (non-negative integer). Returns: The nth Fibonacci number. """ if n <= 1: return n else: return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2) # Get the number of terms from the user num_terms = int(input("Enter the number of Fibonacci terms to generate: ")) if num_terms <= 0: print("Please enter a positive integer.") else: print("Fibonacci sequence:") for i in range(num_terms): print(fibonacci_recursive(i), end=" ") print() # For a newline at the end

Output

 
OUTPUT 1 :
Enter the number of Fibonacci terms to generate: 5
Fibonacci sequence:
0 1 1 2 3  


OUTPUT 2 :
Enter the number of Fibonacci terms to generate: 10
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34 

Explanation:

fibonacci_recursive(n) Function:

  • Base Case:The if n <= 1: condition handles the base cases of the recursion. The first two Fibonacci numbers are defined as 0 and 1. If n is 0 or 1, the function directly returns n.
  • Recursive Case:The else: block handles the recursive step. For any n greater than 1, the function calculates the nth Fibonacci number by recursively calling itself to get the (n-1) th and (n-2) th Fibonacci numbers and summing them.

 

User Input and Output:

 

  • The program prompts the user to enter the desired number of Fibonacci terms.
  • It includes a check to ensure the input is a positive integer.
  • forloop iterates from 0 up to num_terms - 1, calling fibonacci_recursive(i) for each iteration to calculate and print the corresponding Fibonacci number.
  • end=" "is used in the print statement to keep the numbers on the same line, separated by spaces.