简体   繁体   English

此函数应该可以计算出阶乘,但不能。 [蟒-3.X]

[英]This function should work to calculate factorials, but it doesn't. [python-3.x]

(Full disclosure, I am going through the Python tutorial at CodeAcademy, and am using their web-based IDE.) (全面披露,我正在阅读CodeAcademy的Python教程,并正在使用其基于Web的IDE。)

def factorial(x):
    bang = 1
        for num in x:
            bang = bang * num
    return bang

In java, this works to generate a factorial from a number smaller than 2,147,483,647. 在Java中,这可以从小于2,147,483,647的数字生成阶乘。 I think it should work in python, but it doesn't. 我认为它应该在python中工作,但事实并非如此。 Instead I get the error: 相反,我得到了错误:

"Traceback (most recent call last): File "python", line 3, in factorial TypeError: 'int' object is not iterable" “跟踪(最近一次调用最后一次):阶乘TypeError中的文件“ python”,第3行:“ int”对象不可迭代”

Perhaps there's something I'm not understanding here, or perhaps my syntax is wrong. 也许有些东西我在这里不了解,或者我的语法是错误的。 I tested further and created a separate function called factorial that iterates: 我进行了进一步测试,并创建了一个单独的称为阶乘的函数,该函数可以迭代:

def factorial(x):
    if x > 2:
        return x
    else:
        return x(factorial(x-1))

This also doesn't work, giving me the error: 这也行不通,给我错误:

"Traceback (most recent call last): File "python", line 11, in factorial TypeError: 'int' object is not callable" “回溯(最近一次调用最后一次):文件“ python”,第11行,析因TypeError:“ int”对象不可调用”

I am a python noob, but it seems that both of these should work. 我是python noob,但似乎这两个都应该起作用。 Please advise on the best way to learn Python syntax... 请建议学习Python语法的最佳方法...

You can't do for num in x if x is an integer. 如果x是整数,则无法for num in x执行for num in x An integer isn't "iterable" as the error says. 如错误所示,整数不是“可迭代的”。 You want something like this: 您想要这样的东西:

def factorial(x):
    bang = 1
    for num in xrange(1, x+1):
        bang = bang * num
    return bang

The xrange (or range ) will generate the necessary range of numbers for the in to operate upon. xrange (或range )将为in生成必要的数字范围。

def f(x):
        if x < 2:
            return 1
        else:
            return x * f(x - 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM