初学Python 语法无效 *更新

2 投票
1 回答
1156 浏览
提问于 2025-04-17 15:14

我正在为我的一门课完成一个程序,但我总是遇到“语法错误”,对我来说,Python是非常新的东西,所以请多包容我的无知。

这个语法错误出现在“if guess==(num_x+num_y):”这一行的冒号那里。如果有人能帮我,我会非常感激。


更新*
我修正了括号,谢谢你,abarnert,但现在我遇到了一个SyntaxError

Traceback (most recent call last):
  File "C:\Users\Franz\Desktop\randomstudy.py", line 48, in <module>
    main()
  File "C:\Users\Franz\Desktop\randomstudy.py", line 25, in main
    guess=int(input(num_x, "-", num_y, "=\n"))
TypeError: input expected at most 1 arguments, got 4

我已经更新了下面的代码,加入了括号。

def main():
    import random
    num_x=random.randint(-50,50)
    num_y=random.randint(-50,50)
    op=random.randint(0,3)
    control=True 
    print("Welcome! Here is your random problem:\n")   
    if op==0:
        while True:
            guess=int(input(num_x, "+", num_y, "=\n"))
            if guess==(num_x+num_y):
                print("Congratulations! You have answered the problem correctly!")
                break     
            else:
                print("I’m sorry, that is not correct.  Please try again.")
    elif op==1:
        while True:
            guess=int(input(num_x, "-", num_y, "=\n"))
            if guess==(num_x-num_y):
                print("Congratulations! You have answered the problem correctly!")
                break     
            else:
                print("I’m sorry, that is not correct.  Please try again.")
    elif op==2:
        while True:
            guess=int(input(num_x, "*", num_y, "=\n"))
            if guess==(num_x*num_y):
                print("Congratulations! You have answered the problem correctly!")
                break    
            else:
                print("I’m sorry, that is not correct.  Please try again.")
    elif op==3:
        while True:
            guess=int(input(num_x, "/", num_y, "=(Please round to two decimal places)\n"))
            if guess==(num_x/num_y):
                print("Congratulations! You have answered the problem correctly!")
                break    
            else:
                print("I’m sorry, that is not correct.  Please try again.")

main()

1 个回答

6

在那行之前缺少一个')':

    guess=int(input(num_x, "+", num_y, "=\n")
    if guess==(num_x+num_y):

正如Igor在评论中提到的,你还有其他几行也缺少闭合的括号,你也得把它们修好,不然几行之后你又会遇到另一个SyntaxError(语法错误)。你可以考虑使用一些能帮助你检查括号是否配对的编辑器,这样会让你的编程生活轻松很多。

在Python中,这种情况没有其他语言那么常见,但发生的频率也足够高,所以每当你遇到莫名其妙的SyntaxError时,最好先看看前一行。

(在大多数语言中,几乎任何表达式或语句都可以继续到下一行。但在Python中并不是这样——不过如果有一个开放的括号,括号内的表达式是可以继续到下一行的。)

撰写回答