-1

I making a quiz program using Python 3. I'm trying to implement checks so that if the user enters a string, the console won't spit out errors. The code I've put in doesn't work, and I'm not sure how to go about fixing it.

import random
import operator
operation=[
    (operator.add, "+"),
    (operator.mul, "*"),
    (operator.sub, "-")
    ]
num_of_q=10
score=0
name=input("What is your name? ")
class_num =input("Which class are you in? ")
print(name,", welcome to this maths test!")

for _ in range(num_of_q):
    num1=random.randint(0,10)
    num2=random.randint(1,10)
    op,symbol=random.choice(operation)
    print("What is",num1,symbol,num2,"?")
    if int(input()) == op(num1, num2):
        print("Correct")
        score += 1
        try:
            val = int(input())
        except ValueError:
            print("That's not a number!")
    else:
     print("Incorrect")

if num_of_q==10:
    print(name,"you got",score,"/",num_of_q)

2 Answers2

1

You need to catch the exception already in the first if clause. For example:

for _ in range(num_of_q):
    num1=random.randint(0,10)
    num2=random.randint(1,10)
    op,symbol=random.choice(operation)
    print("What is",num1,symbol,num2,"?")
    try:
        outcome = int(input())
    except ValueError:
        print("That's not a number!")
    else:
        if outcome == op(num1, num2):
            print("Correct")
            score += 1
        else:
            print("Incorrect")

I've also removed the val = int(input()) clause - it seems to serve no purpose.

EDIT

If you want to give the user more than one chance to answer the question, you can embed the entire thing in a while loop:

for _ in range(num_of_q):
    num1=random.randint(0,10)
    num2=random.randint(1,10)
    op,symbol=random.choice(operation)
    while True:
        print("What is",num1,symbol,num2,"?")
        try:
            outcome = int(input())
        except ValueError:
            print("That's not a number!")
        else:
            if outcome == op(num1, num2):
                print("Correct")
                score += 1
                break
            else:
                print("Incorrect, please try again")

This will loop eternally until the right answer is given, but you could easily adapt this to keep a count as well to give the user a fixed number of trials.

0

Change

print("What is",num1,symbol,num2,"?")
if int(input()) == op(num1, num2):

to

print("What is",num1,symbol,num2,"?")
user_input = input()
if not user_input.isdigit():
    print("Please input a number")
    # Loop till you have correct input type
else:
    # Carry on

The .isdigit() method for strings will check if the input is an integer. This, however, will not work if the input is a float. For that the easiest test would be to attempt to convert it in a try/except block, ie.

user_input = input()
try:
    user_input = float(user_input)
except ValueError:
    print("Please input a number.")
Christian Witts
  • 11,375
  • 1
  • 33
  • 46