Lesson 5.3: Hangman Pt. 2 – Error Handling

Today’s Goals

  • Make Hangman more user-friendly
  • Add error handling with try/except
  • Prevent the game from crashing on bad input

Warm-Up Question

  • What happens if the user types a number instead of a letter?
  • Or if they type more than one letter?

The Problem

word = "python"
guess = input("Guess a letter: ")

if guess.isalpha() and len(guess) == 1:
    print("Valid guess!")
else:
    print("Invalid input!")

Class Practice

  • Run this code
  • Try entering numbers or multiple letters
  • Why is .isalpha() helpful?

Using try/except

try:
    number = int(input("Enter a number: "))
    print("You typed:", number)
except ValueError:
    print("That was not a number!")

Applying to Hangman

  • Catch errors so the game doesn’t crash
  • Require a single alphabetical character
  • Give feedback if the input is invalid

Student Challenge

  • Add input checking to your Hangman game
  • The program should:
    • Accept only single letters
    • Reject numbers and empty input
    • Print a helpful error message

Wrap-Up

  • Error handling makes games smoother
  • Next time: We’ll play full Hangman together!