Python Forum
How to write a response if a user inputs a string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to write a response if a user inputs a string (/thread-26341.html)



How to write a response if a user inputs a string - horuscope42 - Apr-28-2020

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'



RE: How to write a response if a user inputs a string - deanhystad - Apr-28-2020

try/except
Catch that ValueError exception instead of letting it fall through to the default exception handler.


RE: How to write a response if a user inputs a string - horuscope42 - Apr-29-2020

I was trying to do a try/except but I'm not sure where to place it.

Any advice?


RE: How to write a response if a user inputs a string - deanhystad - Apr-29-2020

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