# 在 Python 中计算阶乘

Sahil Bhosale 2023年1月30日

## 在 Python 中使用迭代法计算一个数的阶乘数

1. 给定的数字是负数。如果这个数字是负数，那么我们将简单地说，我们找不到阶乘，因为负数的阶乘不存在。
2. 给定的数字是零。如果数字是零，那么我们将简单地打印 `1`，因为零的阶乘是 `1`
3. 给定的数字是正数。如果数字是正数，那么我们只需要找到它的阶乘。
``````def factorial(num):
if num < 0:
print("Factorial of negative num does not exist")

elif num == 0:
return 1

else:
fact = 1
while num > 1:
fact *= num
num -= 1
return fact

num = 5

print("Factorial of", num, "is", factorial(num))
``````

``````Factorial of 5 is 120
``````

## 在 Python 中使用递归计算一个数字的阶乘

``````def factorial(n):
return 1 if (n == 1 or n == 0) else n * factorial(n - 1)

num = 5
print("Factorial of", num, "is", factorial(num))
``````

``````Factorial of 5 is 120
``````

## 使用 Python 中的 `math.factorial()` 函数计算一个数字的阶乘

``````from math import factorial

print("Factorial is", factorial(5))
``````

``````Factorial is 120
``````

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.