-1
if op == '+':
    left1 = random.randint(1,100)
    right1 = random.randint(1,100)
    print ("What is " + (str(left1) + op + str(right1) + "?"))
    answer  = eval(str(left1) + op + str(right1))
    guess = int(input(""))
    if guess == answer:
        print("Correct!")
        score + 1
    elif guess != answer:
        print("Incorrect")
    else:
        except ValueError:
            print("Expected integer")

I tried except ValueError, but it stated that it was invalid syntax. I'm trying to get the code to force the user to enter an integer for the answer, if they don't then it tells them that they are supposed to enter an integer.

A MUSE
  • 35
  • 6

1 Answers1

0

ValueError is not a function; it is a class (an Exception subclass).

You need to use except as part of a try statement, it cannot be used on its own; you need to put any code you want 'protected' inside the try:

if op == '+':
    left1 = random.randint(1,100)
    right1 = random.randint(1,100)
    print ("What is " + (str(left1) + op + str(right1) + "?"))
    answer  = eval(str(left1) + op + str(right1))

    try:
        guess = int(input(""))
    except ValueError:
        print("Expected integer")
    else:    
        if guess == answer:
            print("Correct!")
            score = score + 1  # don't forget to *store* the sum!
        else:
            print("Incorrect")

You probably want to read the canonical Stack Overflow question on user input in Python to learn more about this: Asking the user for input until they give a valid response, as well as the section on handling exceptions in the Python tutorial.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343