Lesson 16: Mini-Project: The Number-Guessing Game


What you'll learn in this lesson


The game, in plain words

Before writing any code, say what the program must do, in plain words:

  1. The computer secretly picks a number between 1 and 10.
  2. The player guesses.
  3. After each guess, the computer says "too high", "too low", or "you got it!"
  4. The game counts the guesses and reports the total when the player wins.

That is the entire design. Every line of code below exists to do one of those four steps. When a program feels too big, this is the move: describe it in plain words first, then turn each sentence into code.


A new tool: random

One tool you have not met yet makes this game possible:

guess_text = input("Guess a number from 1 to 10: ")
guess = int(guess_text)
print(guess)

If the player types 7, this prints 7 — as a number now, ready for comparison. (If the player types something that is not a number, int() complains. Handling that gracefully is a nice second version of this game, and a good stretch goal once this version works.)


The whole game

Here it is, complete. Read it top to bottom first, matching each part to the four design steps above, then type it into a file called guessing_game.py and run it:

import random

secret = random.randint(1, 10)
tries = 0

print("I am thinking of a number from 1 to 10.")
print("Can you guess it?")

while True:
    guess_text = input("Your guess: ")
    guess = int(guess_text)
    tries = tries + 1

    if guess == secret:
        print("You got it!")
        print("It took you " + str(tries) + " tries.")
        break
    elif guess < secret:
        print("Too low — try higher.")
    else:
        print("Too high — try lower.")

Play it. A run might look like this (the secret is different every time, so your run will differ):

I am thinking of a number from 1 to 10.
Can you guess it?
Your guess: 3
Too low — try higher.
Your guess: 8
Too high — try lower.
Your guess: 5
You got it!
It took you 3 tries.

How the pieces fit together

Notice what is not here: no new concept except random, input, and break. Everything else is Lessons 1–15, combined. That is the real lesson of this project: programs are not built from advanced magic, but from simple ideas stacked together.


Make it yours

A finished game is a starting point, not an ending. Try one change at a time, and run the game after each change:

Each change is small. Each one teaches something. That is how programmers grow: not by memorizing more, but by changing working programs and watching what happens.


Hands-on exercise

  1. Type the full game into guessing_game.py and play it until you win at least once.
  2. Change the range to 1–20 and play again. What changed about the difficulty, and why?
  3. Add a line at the start that prints how many tries the player has used so far — no, wait: add it at the end instead, next to the win message, so it reads "You got it in 3 tries!" as one sentence.
  4. Pick one "make it yours" idea above and build it.

Quick quiz

  1. What does random.randint(1, 10) do, and why must import random come first?
  2. What does input() give you, and why is int() needed on its answer?
  3. What does while True: mean, and what stops such a loop?
  4. Why is == checked before the too-low and too-high cases?
  5. The game uses no new concept except random, input, and break — what does that tell you about building programs?

Answer key: 1. It picks a whole number from 1 to 10 at random; import random loads the tool, without which Python does not know it. 2. Text typed by the player; int() converts it to a number so it can be compared with the secret. 3. "Repeat forever"; break exits the loop when the player wins. 4. So a correct guess wins at once instead of falling through to a hint. 5. That programs are simple ideas stacked together, not advanced magic.


Key takeaways

Next lesson: What's Next — Stepping into Python 3 Programming.


Slides

Work through the slides with Helio's narration, or download them:

Open the slidesDownload PowerPointDownload PDF

Try it yourself

Run the lesson's example with real Python, right in your browser (Python loads from the internet, so you need to be online).

Open the demo

Practice file

Download lesson16-practice.pyDownload the solution

# Lesson 16: Mini-Project — The Number-Guessing Game
# WHAT TO DO: This is the full guessing game from the lesson. The
# computer picks a secret number from 1 to 10 with random.randint(),
# the player guesses with input(), and the game counts tries. One line
# is unfinished: in the winning branch, fill in line 35 to report how
# many tries it took, for example:
#     print("It took you " + str(tries) + " tries.")
# HINT: str(tries) turns the tries number into text so it can join the
# message with +. Only change the placeholder line, inside the win branch.
# Run with F5 in IDLE and type guesses when asked. You are done when a
# win prints "You got it!" plus a sentence with your number of tries.
# NOTE: If you run this where no one can type a guess (an automated
# check, for example), it prints a message and stops cleanly instead
# of crashing. That is expected — play it in IDLE to play for real.

import random

secret = random.randint(1, 10)
tries = 0

print("I am thinking of a number from 1 to 10.")
print("Can you guess it?")

while True:
    try:
        guess_text = input("Your guess: ")
    except EOFError:
        print("No guess typed, so the game stops here.")
        break
    guess = int(guess_text)
    tries = tries + 1

    if guess == secret:
        print("You got it!")
        print("TODO - how many tries did it take?")  # <-- CHANGE THIS LINE
        break
    elif guess < secret:
        print("Too low - try higher.")
    else:
        print("Too high - try lower.")

Save the file as lesson16-practice.py and run it with F5 in IDLE. On a Mac, if F5 does nothing, use Run, then Run Module, from the menu.

Check yourself

Five quick questions on this lesson. Take the Lesson 16 quiz

Want graded quizzes and progress tracking?

Enroll free in the full course — same 17 lessons, with your progress saved. Free, no payment.