简体   繁体   English

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

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

I'm new to python and I've been trying to improve by creating some practice code.我是 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))))

I've already defined the factorial function earlier in my code and the problem seems to be coming from these two lines.我已经在代码的前面定义了阶乘函数,问题似乎来自这两行。 Is there a syntax error which I don't see??是否存在我没​​有看到的语法错误?

The input function in Python 2 evaluates the user input as Python code rather than taking it literally. Python 2 中的input函数将用户输入评估为 Python 代码,而不是按字面意思理解。 You should use raw_input instead in Python 2:您应该在 Python 2 中使用raw_input代替:

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

Assuming you are using Python 3 since your print statement is a function call.假设您使用的是 Python 3,因为您的打印语句是一个函数调用。 When I tried your code using当我尝试使用您的代码时

import math

then this line instead:那么这一行:

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

the result was:结果是:

10! is equal to 3628800

I entered a 10 as the value.我输入了 10 作为值。 Perhaps the issue is in your factorial function.也许问题出在您的阶乘函数中。 Hard to know unless you post that as well.很难知道,除非你也发帖。

The below code works for me.下面的代码对我有用。 I doubt that there may be a problem in your factorial function.我怀疑您的阶乘函数可能有问题。

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