Catch Invalid Input
Wrap int() in a try/except block so bad input prints a message instead of crashing
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Right now, ask_question calls int(answer_text) with no protection. If the player types abc, the ValueError crashes the quiz.
A try/except block catches the error and runs alternative code instead:
try:
answer = int(answer_text)
except ValueError:
print("Please enter 1, 2, 3, or 4.")
return FalsePython runs the try block. If int() succeeds, the quiz continues normally. If int() raises a ValueError, Python skips the rest of try and runs the except block — printing a message and returning False so the question counts as wrong.
How try/except works
- Python runs the code inside
try. - If no error occurs, Python skips
exceptentirely. - If a
ValueErroroccurs, Python stops thetryblock and runsexcept.
Returning False on bad input is a simple first fix. The player cannot crash the quiz, but a typo counts as a wrong answer. You will improve this in the next chapter.
Instructions
Replace the plain int() call in ask_question with a try/except block.
- Replace
answer = int(answer_text)with atryblock containinganswer = int(answer_text)— wrapping it intrymeans Python will attempt the conversion but hand control toexceptif it fails, instead of crashing. - Add an
except ValueErrorblock. Inside, callprint("Please enter 1, 2, 3, or 4.")and thenreturn False—ValueErroris the specific errorint()raises for non-numeric input;return Falsetreats the bad input as a wrong answer so the quiz can continue without crashing.
QUESTIONS = [
("What is the type of the value 3.14?", "int", "str", "float", "bool", 3),
("What keyword defines a function in Python?", "for", "def", "if", "class", 2),
("What does print() do?", "Stores a value", "Returns a number", "Displays output", "Reads input", 3),
]
def ask_question(text, o1, o2, o3, o4, correct):
print(text)
print()
print(f" 1) {o1}")
print(f" 2) {o2}")
print(f" 3) {o3}")
print(f" 4) {o4}")
print()
answer_text = input("Your answer (1-4): ")
# Step 1: try: answer = int(answer_text)
# Step 2: except ValueError: print message, return False
is_correct = answer == correct
print()
print(f"You answered: {answer}")
if is_correct:
print("Correct!")
else:
print(f"Wrong! The correct answer was option {correct}.")
return is_correct
def show_results(score, total):
print(f"Score: {score}/{total}")
if score == total:
print("Perfect score!")
elif score >= 2:
print("Great job!")
elif score >= 1:
print("Not bad!")
else:
print("Keep practicing!")
def run_quiz(questions=QUESTIONS):
total = len(questions)
score = 0
streak = 0
print("=== Python Quiz ===")
print()
for text, o1, o2, o3, o4, correct in questions:
result = ask_question(text, o1, o2, o3, o4, correct)
if result:
score = score + 1
streak = streak + 1
if streak >= 3:
print(f" Hot streak! ({streak} in a row)")
else:
streak = 0
show_results(score, total)
while True:
run_quiz()
print()
again = input("Play again? (y/n): ")
if again != "y":
break
print("Thanks for playing!")
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding