Lesson 5.1: Intro to Games in Python

Today’s Goals

  • See how Python can be used to build simple text-based games
  • Review input(), print(), and random
  • Modify a number guessing game

Warm-Up Question

  • What’s your favorite game?
  • What makes it fun?
    (Call on 2–3 students)

A Game Is Just…

  • A loop (repeated play)
  • Input from the player
  • Output that reacts
  • Rules that control what happens

First Example: Number Guessing

import random
number = random.randint(1, 10)
guess = int(input("Guess a number 1–10: "))
if guess == number:
    print("You got it!")
else:
    print("Nope, it was", number)

Class Practice

  • Run the code on your computer
  • Play the game a few times
  • What happens if you enter text instead of a number?

Adding Tries

import random
number = random.randint(1, 10)
for i in range(3):
    guess = int(input("Guess: "))
    if guess == number:
        print("Correct!")
        break
    else:
        print("Wrong!")

Discussion

  • Why is the loop useful here?
  • What happens if the user guesses wrong every time?

Student Challenge

  • Add a “You lost!” message if the player never guesses correctly.
  • Bonus: Let the user choose the range of numbers.

Wrap-Up

  • Games are just code with input, loops, and rules
  • Next time: We’ll start building Hangman!