使用 while 循环和 for 循环都可以输出 1!+2!+3!+4!+5! 的结果。以下是使用 while 循环和 for 循环分别输出该结果的示例代码:

使用 while 循环:

total = 0
num = 1

while num <= 5:
    fact = 1
    i = 1
    while i <= num:
        fact *= i
        i += 1
    total += fact
    num += 1

print(total)

使用 for 循环:

total = 0

for num in range(1, 6):
    fact = 1
    for i in range(1, num+1):
        fact *= i
    total += fact

print(total)

输出结果为:

153

以上是输出 1!+2!+3!+4!+5! 的示例代码和结果。你可以根据需要进行相应的调整。

Python 循环计算 1!+2!+3!+4!+5! - while 和 for 循环示例

原文地址: https://www.cveoy.top/t/topic/bnPZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录