The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
# Taking input from the user
number = int(input("Enter a number to find its factorial: "))
print("Factorial of", number, "is", factorial(number))
Enter a number to find its factorial: 5
Factorial of 5 is 120
The function factorial(n)
calculates the factorial of the given non-negative integer n
.
If n
is equal to 0, the factorial is 1. Otherwise, it recursively calculates the factorial by multiplying n
with the factorial of n-1
.
The example usage section demonstrates how to take input from the user, calculate the factorial, and print the result.