繁体   English   中英

为什么我的 python 代码返回语法错误?

[英]Why is my python code returning a syntax error?

我是 python 的新手,我一直在尝试通过创建一些练习代码来改进。

user_number = input('Enter in the number you want the factorial of: ')
print(str(user_number) + '! is equal to ' + str(factorial(int(user_number))))

我已经在代码的前面定义了阶乘函数,问题似乎来自这两行。 是否存在我没​​有看到的语法错误?

Python 2 中的input函数将用户输入评估为 Python 代码,而不是按字面意思理解。 您应该在 Python 2 中使用raw_input代替:

user_number = raw_input('Enter in the number you want the factorial of: ')

假设您使用的是 Python 3,因为您的打印语句是一个函数调用。 当我尝试使用您的代码时

import math

那么这一行:

print(str(user_number) + '! is equal to ' + str(math.factorial(int(user_number))))

结果是:

10! is equal to 3628800

我输入了 10 作为值。 也许问题出在您的阶乘函数中。 很难知道,除非你也发帖。

下面的代码对我有用。 我怀疑您的阶乘函数可能有问题。

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

user_number = input('Enter in the number you want the factorial of: ')
print(str(user_number) + '! is equal to ' + str(factorial(int(user_number))))

暂无
暂无

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

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