Calculating Factorials in Python
The factorial of a non-negative integer (denoted as ) is the product of all positive integers less than or equal to . For , the factorial is defined as 1. Mathematically, it is represented as:
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.