我需要在python中编写一个返回N!的程序,而不使用factorial函数。我有一个程序到目前为止,但我一直收到一个错误,local variable "fact" is assigned but never used
。分配后如何使用fact = 1
?
from pylab import *
def factorial(n):
fact = 1
for i in range(n):
print("i = ", i)
fact = fact * i
print("The factorial of " + str(n) + " is: " + str(fact))
答案 0 :(得分:5)
In [37]: def fact(n):
fac=1
for i in range(2,n+1):
fac *=i
return fac
....:
In [43]: fact(5)
Out[43]: 120
In [44]: fact(6)
Out[44]: 720
答案 1 :(得分:1)
我对python知之甚少,但你应该在这些例子中使用递归。这很简单。递归是一个自称为
的函数def factorial(n):
if n== 0 or n == 1:
return 1
else:
return n * factorial(n-1)