Python Forum

Full Version: How to write a response if a user inputs a string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
def main():
    """
    Create a program that randomly generates simple addition problems for the user,
    reads in the answer from the user, and then checks to see if they got it right or wrong,
    until the user appears to have mastered the material and print a message to congratulate the user.
    """

    answers_right = 0

    while answers_right < 3:

        ran_number_1 = random.randint(10, 99)
        ran_number_2 = random.randint(10, 99)
        solution = ran_number_1 + ran_number_2

        print(f"What is {ran_number_1} + {ran_number_2}?")
        user_answer = int(input("Your answer: "))

        if user_answer == solution:
            answers_right += 1
            print(f"Correct. You've gotten {answers_right} correct in a row.")
        elif user_answer != solution:
            answers_right = 0
            print(f"Incorrect. The expected answer is {solution}.")
        else:
            print("Invalid Response.")
Error:
Traceback (most recent call last): File "C:/Users/Carlo/Documents/Standford Class/Assignment2/khansole_academy.py", line 47, in <module> main() File "C:/Users/Carlo/Documents/Standford Class/Assignment2/khansole_academy.py", line 26, in main user_answer = int(input("Your answer: ")) ValueError: invalid literal for int() with base 10: 'qer'
try/except
Catch that ValueError exception instead of letting it fall through to the default exception handler.
I was trying to do a try/except but I'm not sure where to place it.

Any advice?
There are multiple ways to solve this problem. Perhaps the simplest is convert "solution" to a string instead of converting user_answer to an int.

If you need the answer to be an integer you can catch the exception
try:
   correct_answer = solution == int(user_answer)
except ValueError:
   correct_anser = False

if correct_anser:
   # do correct answer stuff
else:
   # do incorrect answer stuff