用 while 循环写阶乘 python
Write factorial with while loop python
我是新手,对Python了解不多。有人知道如何在 while 循环中编写阶乘吗?
我可以在 if / elif else 语句中实现:
num = ...
factorial = 1
if num < 0:
print("must be positive")
elif num == 0:
print("factorial = 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print(num, factorial)
但我想用 while 循环(无功能)来做到这一点。
while num > 1:
factorial = factorial * num
num = num - 1
如果你只想得到一个结果:math.factorial(x)
While 循环:
def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
我是新手,对Python了解不多。有人知道如何在 while 循环中编写阶乘吗?
我可以在 if / elif else 语句中实现:
num = ...
factorial = 1
if num < 0:
print("must be positive")
elif num == 0:
print("factorial = 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print(num, factorial)
但我想用 while 循环(无功能)来做到这一点。
while num > 1:
factorial = factorial * num
num = num - 1
如果你只想得到一个结果:math.factorial(x)
While 循环:
def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num