In this Python lesson, we will practice how to write a program to calculate the factorial of a number. Factorial is the product of every number from 1 to any given number. The factorial of negative numbers does not exist and the factorial of 0 = 1.
Below is the general formula for factorial.
factorial of n (n!) = 1 * 2 * 3.…n
Let’s take for example, we want to get the factorial of 5. Following the formula stated above, it would simply mean the product of every number from 1 to 5 which is equal to 1 * 2 * 3 * 4 * 5 = 120.
Example: Get a Factorial of any Number
# request input from the user
num = int(input('Enter a number: '))
factorial = 1
# check for negative, positive or zero
if num < 0:
print('Error! Negative number is not accepted')
elif num == 0:
print('Factorial of 0 = 1')
else:
for i in range(1,num + 1):
factorial = factorial*i
print('Factorial of {0} = {1}'.format(num,factorial))
Output
Enter a number: 5
Factorial of 5 = 120
In the above program, we requested the user to insert any number and the user input is stored in the num variable. Using the if…elif…else statement, we checked if the number whose factorial is to be found is negative, positive or zero. If the number is positive, we calculate the factorial using for loop and range() function.