Lesson Complete!

Handle Bad Input

You finished the fourth lesson of Upgrade PyQuiz. The quiz now handles bad input gracefully — no crashes, no silent wrong answers.

Here is the complete quiz.py:

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()
    while True:
        answer_text = input("Your answer (1-4): ")
        try:
            answer = int(answer_text)
        except ValueError:
            print("Please enter 1, 2, 3, or 4.")
            continue
        if answer < 1 or answer > 4:
            print("Please enter 1, 2, 3, or 4.")
            continue
        break
    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!")

What you added:

  • try/except ValueError — catches int() failures so bad input no longer crashes the quiz
  • while True retry loop — re-prompts the player until they enter a valid number
  • continue — skips the rest of the loop body and restarts from the prompt
  • Range check — rejects answers outside 1–4 using if answer < 1 or answer > 4:
  • break — exits the loop only when the input is a valid integer in range

What's still missing: the quiz only has three questions. In the next course, you will store questions in a dictionary, load them from a file, and let players add their own — turning this into a fully customizable quiz tool.