Skip to contentSkip to navigation

Module 06 · Lesson 01

Project: Number Guessing Game

Build a number guessing game step by step: pick a secret with random, loop until the player wins or runs out of attempts, give higher or lower hints, and check the input.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Pick a random secret
  • Hint with if and elif
  • Loop through guesses
  • Test with a function

The game in four parts

The computer picks a secret number. The player guesses, and gets a hint after every wrong guess.

  • Pick a secret

    random.randint(1, 20) picks a whole number from 1 to 20, both ends included.

  • Loop

    Keep taking guesses until the player is right or runs out of tries.

  • Hint

    if, elif and else say too high, too low or correct.

  • Check

    A guess that is not a number gets a friendly message, not a crash.

The same idea, elsewhere

Guess, get a hint, guess again: it powers more than games.

  • Higher or lowerCard and quiz games where each answer narrows the next guess.
  • Daily word puzzlesEach guess colours letters as hints for the next try.
  • Searching fastComputers find a name in a sorted list of millions by guessing the middle and halving.
  • Escape roomsLock codes with clue lights are a guessing loop in hardware.

Picking the secret

One line chooses the number the player must find. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

name:Stores the number so every later guess is checked against the same one.

Build the game in five steps

Build the project one step at a time. Each example runs on its own: change it, then press Run.

Example 1 of 61. Secret

Run this a few times. The secret changes each run.

Your turn: Make the range 1 to 100. Then pick a dice roll from 1 to 6.

Python
import random

secret = random.randint(1, 20)
print("I picked", secret)
Output
Press Run to see what it prints.

Watch a game play itself

Press Step to run one line at a time. The list stands in for three guesses a player typed.

Ready. Press Step to run the first line.

  1. secret = 7
  2. guesses = [10, 4, 7]
  3. for guess in guesses:
  4. if guess < secret:
  5. print(guess, "is too low")
  6. elif guess > secret:
  7. print(guess, "is too high")
  8. else:
  9. print(guess, "is right!")
  10. break

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.The secret is from 1 to 100. Which first guess is smartest?

0 of 6 answered

Common game misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Building the game

The brief

The computer picks a secret whole number from 1 to 20. The player has up to 5 guesses. After each guess the game says whether the secret is higher or lower, or announces a win with the number of attempts used. If the guesses run out, the game reveals the secret.

Plan before you type

Writing the steps in plain words first saves time, because each step turns into a few lines of code and you can test them one at a time.

  1. Pick a random secret and set the attempt counter to 0.
  2. While the player still has attempts left: read a guess and count it.
  3. If the guess is correct, congratulate the player and stop the loop.
  4. Otherwise say higher or lower.
  5. After the loop, if the player never won, reveal the secret.

Step 1: a random secret

The random module from the standard library makes random choices. random.randint(1, 20) returns a whole number from 1 to 20, including both ends, unlike range().

Try it 1: edit me, then Run
import random
secret = random.randint(1, 20)
Output
Press Run to see what it prints.

While you are building and testing, random numbers make bugs hard to repeat. Calling random.seed(7) first makes the sequence of "random" numbers the same on every run. Remove it once the game works.

Step 2: the main loop

A while loop fits because we do not know how many guesses the player will need. The condition stops it when the attempts run out, and break stops it early on a win.

Try it 2: edit me, then Run
MAX_ATTEMPTS = 5
attempts = 0
won = False
while attempts < MAX_ATTEMPTS:
    guess = int(input("Your guess (1-20): "))
    attempts += 1
    if guess == secret:
        print(f"Correct! You took {attempts} attempts.")
        won = True
        break
    elif guess < secret:
        print("Higher")
    else:
        print("Lower")
if not won:
    print(f"Out of guesses. It was {secret}.")
Output
Press Run to see what it prints.

The counter goes up before the check, so the winning guess is counted too. The won flag remembers whether the loop ended with a break. A loop else would also work here, since it runs only when no break happened, but a named flag is easier for most readers.

Step 3: checking the input

int(input()) crashes with ValueError if the player types ten or just presses Enter. Strings have a method for this check: text.isdigit() is True only when every character is a digit. A small function can keep asking until it gets a valid number in range.

Try it 3: edit me, then Run
def read_guess(low, high):
    while True:
        text = input(f"Your guess ({low}-{high}): ").strip()
        if text.isdigit() and low <= int(text) <= high:
            return int(text)
        print("Please type a whole number in range.")
Output
Press Run to see what it prints.

The while True loop only ends through return, which happens once the input is good. An invalid answer is not counted as an attempt, which is fairer to the player.

Step 4: functions that can be tested

Mixing input() and game rules in one place makes the rules hard to test, because a person has to type each time. Pull the rule into a function that takes values and returns a message:

Try it 4: edit me, then Run
def hint(guess, secret):
    if guess == secret:
        return "correct"
    if guess < secret:
        return "higher"
    return "lower"
Output
Press Run to see what it prints.

Now the game loop calls hint(), and you can test it directly with hint(3, 7) without playing a round. The Lab tasks for this project work this way: guesses come from a list instead of the keyboard, so every run gives the same output and can be checked automatically.

Step 5: putting it together

The finished program reads from the top: imports, constants, functions, then a short main section that uses them. When the pieces are named well, the main section reads almost like the plan you started with. Good next steps are a play-again loop around the whole game, a difficulty setting that changes the range and the number of attempts, and a best score kept between rounds.

Testing the finished game

Before calling the game finished, play it on purpose to break it. Win on the first guess and on the last allowed guess. Lose completely. Type a word, a negative number, a decimal and nothing at all. Guess 1 and 20, the two ends of the range. Each of these is a separate path through the code, and each one has caught a real bug in somebody's game.

A smarter player

There is a neat strategy for this game. Always guess the middle of the range that is still possible, then throw away the half the hint rules out. Each guess halves the possibilities, so 1 to 20 never needs more than 5 guesses, and 1 to 100 never needs more than 7. This idea, called binary search, is one of the most useful algorithms in computing, and one of the Lab tasks traces it.

Syntax

The general shape of the statements in this lesson.

syntax.py
import random
random.seed(7)                  # repeatable while testing
secret = random.randint(1, 20)  # 1 to 20, both included
while attempts < MAX_ATTEMPTS:
    ...
    if guess == secret:
        break
text.isdigit()                  # check before int(text)
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

The game with a list of guesses

Beginner

Run the full game logic with a fixed secret and a list of guesses instead of input(), so the output is the same every time.

Python
def hint(guess, secret):
    if guess == secret:
        return "correct"
    if guess < secret:
        return "higher"
    return "lower"

secret = 13
guesses = [10, 15, 12, 13, 18]
attempts = 0
for guess in guesses:
    attempts += 1
    result = hint(guess, secret)
    print(f"{guess}: {result}")
    if result == "correct":
        print(f"Won in {attempts} attempts")
        break
else:
    print(f"Out of guesses. It was {secret}.")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The list stands in for the player. The loop stops at the fourth guess with break, so 18 is never used, and the loop's else does not run. Changing the list lets you test winning on the first guess, the last guess, or never.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Comparing the guess as text

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
secret = 7
guess = input("Guess: ")
if guess == secret:
    print("Correct!")
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Never prints Correct!, even when the player types 7

Write this instead

secret = 7
guess = int(input("Guess: "))
if guess == secret:
    print("Correct!")

Why it happens

input() returns the string "7", and a string never equals the number 7.

In the real world

Where this shows up in software people use every day.

  1. Finding a page in a book

    Everyday life

    Looking up page 137 in a 300 page book, most people open near the middle and adjust. The halving strategy from the game finds any page in very few steps.

    Why Python fits

    Each step looks at the middle of the pages still possible and discards half of them. Even a 300 page book needs at most 9 steps this way, the same reason a 1 to 100 guessing game never needs more than 7 guesses.

    Python
    target = 137
    low, high = 1, 300
    steps = 0
    while True:
        steps += 1
        middle = (low + high) // 2
        if middle == target:
            break
        if middle < target:
            low = middle + 1
        else:
            high = middle - 1
    print(f"Found page {target} in {steps} steps")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Why do the Labs use a list of guesses?

Automatic checks cannot type into input(). A list gives the same guesses every run, so the expected output is always the same.

How do I add a play-again option?

Wrap the whole game in while True:, ask at the end whether to play again, and break if the answer is not yes.

Is the computer's number really random?

It is pseudo-random: a formula that produces numbers that look random. That is why a seed can repeat the same sequence.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.