Python Program to Find the Factorial of a Number
The factorial of a non-negative integer is the product of all positive integers less than or equal to that number. It is denoted by the symbol “!” and is defined as follows:
n! = n × (n-1) × (n-2) × … × 3 × 2 × 1
For example, 5! (read as “five factorial”) is equal to:
5! = 5 × 4 × 3 × 2 × 1 = 120
Similarly, 0! is defined to be 1.
Factorials are used in many mathematical applications, such as in combinatorics to count the number of ways to arrange objects, and in probability theory to calculate the number of possible outcomes of an event
Python Code :
The Below Python program finds the factorial of a given number:
# Get input number from user num = int(input("Enter a number: ")) # Initialize factorial to 1 factorial = 1 # Calculate factorial of the number if num < 0: print("Factorial does not exist for negative numbers") elif num == 0: print("Factorial of 0 is 1") else: for i in range(1, num + 1): factorial *= i print("Factorial of", num, "is", factorial)
In this program, the user is prompted to enter a number. The program then calculates the factorial of the number using a for loop.
The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5! is equal to 5 * 4 * 3 * 2 * 1, which is 120.
To calculate the factorial of a number, the program initializes the variable factorial to 1. If the number is less than 0, the program prints out a message saying that the factorial does not exist for negative numbers. If the number is 0, the program prints out a message saying that the factorial of 0 is 1. Otherwise, the program uses a for loop to calculate the factorial of the number. For each value of i in the range from 1 to num, the program multiplies the current value of factorial by i using the expression factorial *= i. Finally, the program prints out a message saying what the factorial of the number is using the print statement.
Note that this program assumes that the user enters a valid integer. If the user enters an invalid input, such as a string or a non-numeric value, the program will raise a ValueError or produce an incorrect result.
For example :
Enter a number: 5 Factorial of 5 is 120