pythonsyntax

New to python invalid syntax


I'm trying to finish a program for one of my classes but I keep getting invalid syntax, python is extremely new to me so bear with my ignorance.

The invalid syntax is popping up at the colon in "if guess==(num_x+num_y):" If anyone could help I would much appreciate it.

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.")

Solution

  • The line right before that is missing a ')':

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

    As Igor points out in the comments, you have other lines that are also missing closing parentheses, and you have to fix them as well, or you'll just get another SyntaxError a few lines down. You may want to consider using an editor that helps out with balancing parentheses and similar problems—it certainly makes my life a lot easier.

    This isn't quite as common in Python as with most other languages, but it does happen often enough that you should be used to looking at the previous line whenever you get an inexplicable SyntaxError.

    (In most languages, almost any expression or statement can continue onto the next line. That's not true in Python—but if there's an open parenthesis, the parenthesized expression is allowed to continue onto the next line.)