学校中的“经典”阶乘函数是一个递归定义:
def fact(n):
rtr=1 if n<=1 else n*fact(n-1)
return rtr
n = int(input("Enter n: "))
print fact(n)
如果您只是想要一种方法来解决您的问题:
num = 1
n = int(input("Enter n: "))
while n > 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
如果您想测试小于 1 的数字:
num = 1
n = int(input("Enter n: "))
n=1 if n<1 else n # n will be 1 or more...
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
或者,在输入后测试 n:
num = 1
while True:
n = int(input("Enter n: "))
if n>0: break
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
这是使用reduce的一种功能方式:
>>> n=10
>>> reduce(lambda x,y: x*y, range(1,n+1))
3628800