How to print factorial of a number in Python

Published on Aug. 22, 2023, 12:16 p.m.

To print the factorial of a number in Python, you can use a loop or the math.factorial() function.

Using a loop:

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

if num < 0:
    print("Factorial does not exist for negative numbers.")
else:
    for i in range(1,num+1):
        factorial = factorial*i
    print("The factorial of", num, "is", factorial)

In this program, we first prompt the user to enter a number using the input() function, and then convert the input to an integer using the int() function. We then check if the number is negative, and if it is, we print a message stating that the factorial does not exist for negative numbers. If the number is not negative, we use a for loop to calculate the factorial of the number by multiplying each number from 1 to the input number. Finally, we use the print() function to display the result to the user.

Using the math.factorial() function:

import math

num = int(input("Enter a number: "))

if num < 0:
    print("Factorial does not exist for negative numbers.")
else:
    factorial = math.factorial(num)
    print("The factorial of", num, "is", factorial)

In this program, we first import the math module to access the factorial() function, and then prompt the user to enter a number using the input() function, and then convert the input to an integer using the int() function. We then check if the number is negative, and if it is, we print a message stating that the factorial does not exist for negative numbers. If the number is not negative, we use the math.factorial() function to calculate the factorial of the number. Finally, we use the print() function to display the result to the user.

Both programs will output the factorial of the input number based on the input provided by the user.

Tags:

related content