Python 阶乘代码不工作

Python 阶乘代码不工作,python,Python,不知道出了什么问题,代码给出的是12而不是24 def factorial(x): m=x-1 while m>0: t=x*m m-=1 return t else: return 1 print factorial(4) 您的代码在第一次迭代时返回值,并且在每次迭代时为t分配新值 def factorial(x): ... t = 1 ... while x>0: ...

不知道出了什么问题,代码给出的是12而不是24

def factorial(x):
    m=x-1
    while m>0:
        t=x*m
        m-=1
        return t
    else:
        return 1
print factorial(4)

您的代码在第一次迭代时返回值,并且在每次迭代时为t分配新值

def factorial(x):
...     t = 1
...     while x>0:
...         t *= x
...         x-=1
... 
...     return t
print factorial(4)
output:
24
----或----


因为您将返回while循环的第一次迭代。这不是唯一的问题,
t=x*m
没有意义。虽然OP显然在使用Python 2,但需要注意的是,第二个示例不会像Python 3那样工作,由于
reduce
不再在std库中,必须从
functools
@DeepSpace导入,谢谢您指出这一点。当我切换到Python3时,我将把它写到我的笔记中。谢谢,我知道我的t值一直在变化,所以代码只返回第一个值。但是我不明白你的代码是什么does@Anonymous第一种情况是输入为0时,返回1。第二种情况,当输入不为0时,每次减少输入1直到0。例如,输入为4,x将为4,3,2,1,0(不计数),t将为4,12,24,24@Anonymous我的代码使用reduce和mul来做同样的事情
from operator import mul
def factorial(x):
   return reduce(mul, range(1,x+1))
print factorial(4)
output:
24