In this tutorial, we will learn how to calculate the factorial of a number using Python.
The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!.
The formula for factorial is:
n! = n × (n - 1) × (n - 2) × ... × 1
Below is a simple Python program to calculate the factorial of a number:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Input from the user
num = int(input("Enter a number: "))
result = factorial(num)
print("The factorial of", num, "is", result)
To run the program, follow these steps:
python filename.py
Here is an example of what the output will look like:
Enter a number: 5
The factorial of 5 is 120
In this tutorial, you learned how to calculate the factorial of a number using a recursive function in Python. You can experiment with different values to see how the output changes.