深度阅读

How to print factorial of a number in Python

作者
作者
2023年08月22日
更新时间
18.17 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。