Python Tutorial (33) - Example: Factorial Example

Time: Column:Python views:222

Calculating Factorials in Python

The factorial of a non-negative integer nn (denoted as n!n!) is the product of all positive integers less than or equal to nn. For n=0n = 0, the factorial is defined as 1. Mathematically, it is represented as:

n!=1×2×3××nn! = 1 \times 2 \times 3 \times \ldots \times n

Example

#!/usr/bin/python3

# Filename: test.py
# Author: www.runoob.com

# Calculate factorial of a number provided by the user

# Get user input
num = int(input("Enter a number: "))
factorial = 1

# Check if the number is negative, zero, or positive
if num < 0:
    print("Sorry, factorial does not exist for negative numbers.")
elif num == 0:
    print("The factorial of 0 is 1.")
else:
    for i in range(1, num + 1):
        factorial *= i
    print(f"The factorial of {num} is {factorial}.")

Example Output:

Enter a number: 3
The factorial of 3 is 6.

In this example, the program calculates the factorial of a number input by the user. It handles negative numbers by printing an appropriate message, and it computes the factorial for non-negative numbers using a simple loop.