nathanwailes

Recursion

Jun 9th, 2024
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.52 KB | None | 0 0
  1. """
  2. The simplest possible example of recursion in Python is the calculation of the factorial of a number.
  3.  
  4. This simple example demonstrates the basic concept of recursion: a function calling itself to solve a smaller instance of the same problem, with a base case to terminate the recursion.
  5. """
  6. def factorial(n):
  7.     # Base case: if n is 0, return 1
  8.     if n == 0:
  9.         return 1
  10.     # Recursive case: n * factorial of (n-1)
  11.     else:
  12.         return n * factorial(n-1)
  13.  
  14. # Example usage
  15. print(factorial(5))  # Output: 120
Advertisement
Add Comment
Please, Sign In to add comment