Python Factorial Tutorial

In this tutorial, we will learn how to calculate the factorial of a number using Python.

What is Factorial?

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!.

Factorial Formula

The formula for factorial is:

n! = n × (n - 1) × (n - 2) × ... × 1

Python Code Example

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)
    

How to Run the Program

To run the program, follow these steps:

  1. Open your terminal or command prompt.
  2. Navigate to the directory where your Python file is saved.
  3. Run the program using the command:
  4. python filename.py
  5. When prompted, enter a number and press Enter.

Example Output

Here is an example of what the output will look like:


Enter a number: 5
The factorial of 5 is 120
    

Conclusion

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.