Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function for factorial - Python Program

Example 1 :

def factorial(n): """Return factorial of n using recursion.""" if n == 0 or n == 1: return 1 return n * factorial(n-1) print(factorial(5))

Output

 
OUTPUT  :
120 

Example 2 :

def factorial_recursive(n): """ Calculates the factorial of a non-negative integer using recursion. Args: n: A non-negative integer. Returns: The factorial of n. """ if n == 0 or n == 1: # Base case: Factorial of 0 or 1 is 1 return 1 else: # Recursive case: n * factorial of (n-1) return n * factorial_recursive(n - 1) # Example Usage and Output: number = int(input("Enter a number : ")) if number < 0: print("Factorial is not defined for negative numbers.") else: result = factorial_recursive(number) print(f"The factorial of {number} is {result}") number_zero = 0 result_zero = factorial_recursive(number_zero) print(f"The factorial of {number_zero} is {result_zero}") number_one = 1 result_one = factorial_recursive(number_one) print(f"The factorial of {number_one} is {result_one}")

Output

 
OUTPUT  :
Enter a number  : 5
The factorial of 5 is 120
The factorial of 0 is 1
The factorial of 1 is 1

Explanation:

factorial_recursive(n) function:

This function takes an integer n as input.

Base Case:

The if n == 0 or n == 1: condition represents the base case of the recursion. The factorial of 0 and 1 is defined as 1. This condition prevents infinite recursion and provides a stopping point.

Recursive Case:

The else: block handles the recursive step. It returns the product of n and the result of calling factorial_recursive with n - 1. This means the function calls itself with a smaller input, gradually moving towards the base case.

How it works (example with n=5):

  • factorial_recursive(5)calls 5 * factorial_recursive(4)
  • factorial_recursive(4)calls 4 * factorial_recursive(3)
  • factorial_recursive(3)calls 3 * factorial_recursive(2)
  • factorial_recursive(2)calls 2 * factorial_recursive(1)
  • factorial_recursive(1)returns 1 (base case)
  • The results are then multiplied back up the call stack: 2 * 1 = 2, then 3 * 2 = 6, then 4 * 6 = 24, and finally 5 * 24 = 120.