def factorial(n):
# Base case: If n is 0 or 1, the factorial is 1.
if n == 0 or n == 1:
return 1
else:
# Recursive case: n! = n * (n-1)!
# Here, we multiply n by the factorial of (n-1).
return n * factorial(n-1)
# Example usage:
# Get input from the user (assumes the user enters a non-negative integer).
num = int(input("Enter a non-negative integer: "))
# Check if the input is negative.
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
# Calculate the factorial using the factorial function.
result = factorial(num)
# Display the result to the user.
print(f"The factorial of {num} is: {result}")
Output:
Enter a non-negative integer: 5
The factorial of 5 is: 120