To calculate the factorial of a number using recursion in Python, you can use the following code:
def factorial(n):
# Base case: if n is 0 or 1, return 1
if n == 0 or n == 1:
return 1
# Recursive case: call factorial function with n-1 and multiply it with n
else:
return n * factorial(n-1)
# Test the function
number = int(input("Enter a number: "))
print("The factorial of", number, "is", factorial(number))
In this code, the factorial
function takes an integer n
as input and calculates the factorial of n
. The base case specifies that if n
is 0 or 1, the function should return 1. For any other value of n
, the function calls itself recursively with n-1
as the input and multiplies the result with n
. This continues until we reach the base case.
To test the function, you can ask the user to enter a number and then call the factorial
function with that number as the input. The result is then printed.