def factorial(x):
hold = 1
count = x
if x == 0:
return 1
else:
while count > 0:
hold *= count
count -= 1 # moved this statement to the bottom
return hold
但更好的功能是:
def factorial(x):
hold = 1
for number in xrange(2, x+1): # or range in python 3
hold *= number
return hold
它返回
0
,因为count
将最终0
在您的最后一个循环中。循环将对count = 1
执行,并且您将用hold乘以0
,因为您在相乘之前从count中减去1
。乘法后必须减去1
:但更好的功能是:
相关问题 更多 >
编程相关推荐