Mini-Project: The Number-Guessing Game

 

What you’ll learn in this lesson

  • How a whole program is assembled from the ideas in Lessons 1–15
  • How to pick a secret number with random
  • How to read the player’s guess with input
  • How a loop, an if chain, and a counter work together
  • How to test your game and make it yours

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:

  • random is a built-in tool for chance. random.randint(1, 10)
    picks a whole number from 1 to 10, with each number equally likely.
    Like Turtle, it must be loaded first: import random.
  • You already know input() from Lesson 7 — it asks the player for a guess.
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

  • while True: means “repeat forever, until something stops the
    loop.” That something is break, which exits the loop the
    moment the player wins. Without break, the game would never end —
    the infinite-loop mistake from Lesson 9, used deliberately here as
    the design.
  • The if/elif/else chain (Lesson 8) gives exactly one
    response per guess: equal, too low, or too high. Because == is
    checked first, a correct guess never falls through to the hints.
  • tries = tries + 1 (Lesson 4) counts guesses, and str(tries)
    (Lesson 12) converts the count to text so it can join the final
    message.
  • random.randint(1, 10) picks a fresh secret every run, so the
    game is different each time you play — the reason it stays fun
    after the first win.

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:

  • Change the range to 1–100 for a harder game.
  • Count down from 5 guesses instead of counting up, and end the game
    with a “you ran out of guesses” message when the count hits zero.
  • Track the player’s best score across rounds (hint: a variable that
    survives from one game to the next, kept outside the loop).
  • Handle a non-number guess gracefully instead of letting int()
    complain (hint: check the guess text before converting it, or learn
    about try in the main Python 3 course).

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.

Mini-Project: The Number-Guessing Game

Python for Absolute Beginners · Lesson 16

What you’ll learn

  • How a whole program is assembled from the ideas in Lessons 1–15
  • How to pick a secret number with random
  • How to read the player's guess with input
  • How a loop, an if chain, and a counter work together
  • How to test your game and make it yours
1 / 13

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
  • Every line of code below exists to do one of those four steps
2 / 13

A new tool: random

  • random is a built-in tool for chance: random.randint(1, 10) picks a whole number from 1 to 10
  • Like Turtle, it must be loaded first: import random
  • You already know input() from Lesson 7 — it asks the player for a guess.
3 / 13

Reading a guess

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

7

If the player types 7, this prints 7 — as a number now, ready for comparison.

4 / 13

The whole game — part 1: setup and loop

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

The secret is picked once, the counter starts at zero, and the loop repeats until the player wins.

5 / 13

The whole game — part 2: hints and win

    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.")

Exactly one response per guess: equal, too low, or too high. Break exits the loop the moment the player wins.

6 / 13

A sample run

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.

The secret is different every time, so your run will differ — that is why the game stays fun.

7 / 13

How the pieces fit together

  • while True means “repeat forever, until something stops the loop” — that something is break
  • Without break, the game would never end: the infinite-loop mistake from Lesson 10, used deliberately here
  • The if / elif / else chain gives exactly one response per guess, and == is checked first
  • tries = tries + 1 counts guesses; str(tries) converts the count to text for the final message
  • random.randint(1, 10) picks a fresh secret every run, so the game is different each time
8 / 13

Make it yours

  • Change the range to 1–100 for a harder game
  • Count down from 5 guesses instead of counting up, and end with a “you ran out of guesses” message
  • Track the player's best score across rounds, with a variable kept outside the loop
  • Handle a non-number guess gracefully instead of letting int() complain
  • Try one change at a time, and run the game after each change
9 / 13

Hands-on exercise

  • Type the full game into guessing_game.py and play it until you win at least once
  • Change the range to 1–20 and play again — what changed about the difficulty, and why?
  • Add a line at the end, next to the win message, so it reads “You got it in 3 tries!” as one sentence
  • Pick one “make it yours” idea above and build it
10 / 13

Key takeaways

  • Design in plain words first: four sentences became the whole game.
  • random.randint() picks a secret; input() reads the player; int() converts text to a number.
  • while True: plus break repeats until the win condition ends it.
  • The if/elif/else chain gives exactly one response per guess.
  • Change a working program one thing at a time — that is how programmers grow.
11 / 13

Take the quiz

Take the Lesson 16 quiz — 5 quick questions to check what you learned.

12 / 13

Next lesson

What's Next: Stepping into Python 3 Programming

13 / 13

Press play on any slide and the lesson plays on by itself from there. You can still click Next or click a slide to move on.

Download the Lesson 16 slides (PowerPoint, with narration)

Download the Lesson 16 slides (PDF)


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.

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

The lesson’s game, with one demo change: the secret number is fixed at 7 for demo purposes, so you can test the logic. In the real game you write in IDLE, the secret is random every time (random.randint(1, 10)). Guess a number from 1 to 10, press Run, and real Python tells you too low, too high, or you got it.

Loading Python… this can take a few seconds the first time. Please wait — the Run button will become available when Python is ready.

Try this: Guess 5 first (too low), then 9 (too high), then 7 — and watch Python’s message change each time.

The code that checks each guess (real Python)



Output

Press Run to make your first guess.
Demo secret = 7 (fixed, so you can learn the logic). The full game in Lesson 16 picks a fresh random secret every run — run it in IDLE to play for real.

Practice file

Save this as lesson16-practice.py and run it with F5 in IDLE.

# 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.")

Key takeaways

  • Design in plain words first: four sentences became the whole game.
  • random.randint() picks a secret; input() reads the player; int() converts text to a number.
  • while True: plus break repeats until the win condition ends it.
  • The if/elif/else chain gives exactly one response per guess.
  • Change a working program one thing at a time — that is how programmers grow.

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


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.