# 在 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.