2

我正在尝试为我的一个课程完成一个程序,但我不断收到无效的语法,python 对我来说是非常新的,所以请忍受我的无知。

无效语法在“if guess==(num_x+num_y):”中的冒号处弹出,如果有人能提供帮助,我将不胜感激。


update* 修复了括号谢谢 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()
4

1 回答 1

6

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

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

正如 Igor 在评论中指出的那样,您还有其他行也缺少右括号,您也必须修复它们,否则您只会再写SyntaxError几行。您可能需要考虑使用有助于平衡括号和类似问题的编辑器——它肯定让我的生活更轻松。

这在 Python 中并不像在大多数其他语言中那样常见,但它确实经常发生,以至于你应该习惯于在遇到莫名其妙的SyntaxError.

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

于 2013-02-08T11:02:34.563 回答