Python Projects · Lesson 144 of 149

Python Project Number Guessing Game

What you will build

  • A number guessing game for the terminal
  • Using functions, loops, conditions, exceptions and random
  • Separating logic from input and output, so it can be tested
  • A scripted demo and unit tests

1. The idea

The computer picks a secret number from 1 to 100. The player has seven tries. After each guess the game says "too low" or "too high", until the player is right or runs out of tries. Mistakes such as typing letters must not crash the game.

Why seven tries? If you always guess the middle of the remaining range, each answer halves it: 100 → 50 → 25 → 13 → 7 → 4 → 2 → 1. Seven well-chosen guesses always suffice for 100 numbers. That is binary search (lesson 18.5 on how time grows).

2. The plan

A good program is built from small pieces, each with one job (lesson 11.8):

Piece Job
judge(guess, secret) compare a guess with the secret: "low", "high" or "correct"
parse_guess(text, low, high) turn the player's text into a valid number, or raise ValueError
play(secret, ask, show, ...) run one game, using ask to get text and show to display messages
main() pick a secret and call play with the real input and print

The key design decision: play never calls input() or print() directly. It receives two functions, ask and show. In real use they are input and print. In a test they can be fakes that supply prepared answers and record the messages (lessons 13.9 and 18.2). This makes the whole game testable without a human.

3. The code

guess.py:

"""Number guessing game.

The game logic is kept apart from input and output so that it can be tested.
"""

import random


def judge(guess: int, secret: int) -> str:
    """Return 'low', 'high' or 'correct' for a guess."""
    if guess < secret:
        return "low"
    if guess > secret:
        return "high"
    return "correct"


def parse_guess(text: str, low: int, high: int) -> int:
    """Turn the player's text into a number in range, or raise ValueError."""
    try:
        number = int(text.strip())
    except ValueError:
        raise ValueError(f"'{text.strip()}' is not a whole number") from None
    if not low <= number <= high:
        raise ValueError(f"please choose a number from {low} to {high}")
    return number


def play(secret, ask, show, low=1, high=100, max_tries=7):
    """Run one game. 'ask' returns the player's text, 'show' displays a message.

    Returns the number of tries used, or None if the player ran out of tries.
    """
    show(f"I am thinking of a number from {low} to {high}. You have {max_tries} tries.")
    tries = 0
    while tries < max_tries:
        try:
            guess = parse_guess(ask(f"Guess {tries + 1}: "), low, high)
        except ValueError as error:
            show(f"  {error}")           # a bad entry does not use up a try
            continue
        tries += 1
        result = judge(guess, secret)
        if result == "correct":
            show(f"  Correct! You needed {tries} {'try' if tries == 1 else 'tries'}.")
            return tries
        show(f"  Too {result}.")
    show(f"  Out of tries. The number was {secret}.")
    return None


def main():
    rng = random.Random()
    secret = rng.randint(1, 100)
    play(secret, input, print)


if __name__ == "__main__":
    main()

How it works:

  • judge is three ifs (lesson 5.2). It returns a word, not a message: the caller decides how to show it.
  • parse_guess converts text to an integer. int("abc") raises ValueError; the function catches it and raises a friendlier ValueError of its own, with from None to hide the technical original (lesson 14.7). It also rejects numbers outside the range. Callers need only catch one exception type.
  • play loops while tries remain (lesson 6.1). The try/except around parse_guess shows the problem and uses continue to ask again without counting a try. A correct guess ends the game by returning the number of tries. After the loop, the player has failed, and None is returned.
  • main creates a random generator (lesson 17.2), picks the secret and plays with the real input and print. The last two lines run main() only when the file is run directly (lesson 16.2).

To play, run python guess.py in a terminal.

Quick check: why does `play` take `ask` and `show` as parameters instead of calling `input` and `print`?

So tests and demos can supply prepared answers and capture the messages, with no human at the keyboard.

4. A scripted run

To see the game working without typing, a small helper pretends to be the player by reading answers from a list (and echoing them, as the terminal would):

import random

from guess import play


def scripted(answers):
    """Return an 'ask' function that gives the next prepared answer."""
    items = iter(answers)

    def ask(prompt):
        answer = next(items)
        print(f"{prompt}{answer}")
        return answer

    return ask


secret = random.Random(2026).randint(1, 100)
print("secret chosen by seed 2026:", secret)
print("--- game 1")
result = play(secret, scripted(["50", "abc", "150", "75", str(secret)]), print)
print("tries:", result)
print("--- game 2 (out of tries)")
result = play(42, scripted(["10", "20", "30", "40", "41", "43", "44"]), print)
print("tries:", result)

Output:

secret chosen by seed 2026: 16
--- game 1
I am thinking of a number from 1 to 100. You have 7 tries.
Guess 1: 50
  Too high.
Guess 2: abc
  'abc' is not a whole number
Guess 2: 150
  please choose a number from 1 to 100
Guess 2: 75
  Too high.
Guess 3: 16
  Correct! You needed 3 tries.
tries: 3
--- game 2 (out of tries)
I am thinking of a number from 1 to 100. You have 7 tries.
Guess 1: 10
  Too low.
Guess 2: 20
  Too low.
Guess 3: 30
  Too low.
Guess 4: 40
  Too low.
Guess 5: 41
  Too low.
Guess 6: 43
  Too high.
Guess 7: 44
  Too high.
  Out of tries. The number was 42.
tries: None

(The secret 16 comes from the seed 2026 on the check computer's Python 3.13.) Notice in game 1 that the two bad entries (abc and 150) produced messages but the guess number stayed at 2: they did not cost a try. In game 2 the player used all seven tries.

5. Tests

Because the logic is separate, unit tests (lesson 18.2) are short. test_guess.py:

import unittest

from guess import judge, parse_guess, play


def scripted(answers):
    items = iter(answers)
    return lambda prompt: next(items)


class TestJudge(unittest.TestCase):
    def test_low_high_correct(self):
        self.assertEqual(judge(10, 50), "low")
        self.assertEqual(judge(90, 50), "high")
        self.assertEqual(judge(50, 50), "correct")


class TestParse(unittest.TestCase):
    def test_valid(self):
        self.assertEqual(parse_guess(" 42 ", 1, 100), 42)

    def test_boundaries(self):
        self.assertEqual(parse_guess("1", 1, 100), 1)
        self.assertEqual(parse_guess("100", 1, 100), 100)

    def test_rejects_text_and_out_of_range(self):
        for bad in ["abc", "", "3.5", "0", "101", "-4"]:
            with self.subTest(bad=bad):
                with self.assertRaises(ValueError):
                    parse_guess(bad, 1, 100)


class TestPlay(unittest.TestCase):
    def test_win_on_third_try(self):
        messages = []
        tries = play(40, scripted(["10", "90", "40"]), messages.append)
        self.assertEqual(tries, 3)
        self.assertIn("Correct", messages[-1])

    def test_bad_input_does_not_cost_a_try(self):
        tries = play(40, scripted(["x", "999", "40"]), lambda m: None)
        self.assertEqual(tries, 1)

    def test_out_of_tries(self):
        messages = []
        tries = play(40, scripted(["1"] * 7), messages.append, max_tries=7)
        self.assertIsNone(tries)
        self.assertIn("The number was 40", messages[-1])


if __name__ == "__main__":
    unittest.main()

Running it printed Ran 7 tests and OK. The tests cover the boundaries (1 and 100), bad input, and the two ways a game can end. Passing messages.append as show collects every message in a list for inspection.

6. The best strategy

A computer player that always guesses the middle of the remaining range needs at most seven tries for 1 to 100:

low, high, tries = 1, 100, 0
secret = 83
while True:
    tries += 1
    mid = (low + high) // 2
    if mid == secret:
        break
    if mid < secret:
        low = mid + 1
    else:
        high = mid - 1
print("binary search needs", tries, "tries for", secret)
binary search needs 7 tries for 83

So a perfect player always wins within seven tries, and the game is fair but not trivial.

7. Ideas to extend it

  1. Difficulty levels: easy (1 to 50, 10 tries), hard (1 to 1000, 10 tries). Pass low, high and max_tries to play.
  2. Play again? Ask after each game and repeat in a loop in main.
  3. Score keeping: remember the best (lowest) number of tries in a file (lessons 15.1 and 15.7).
  4. Hints: after three wrong guesses say whether the secret is even or odd.
  5. Reverse game: you pick a number and the computer guesses by binary search; you answer "higher" or "lower".
  6. A graphical or web version later, reusing judge, parse_guess and play unchanged: this is the reward of separating logic from input and output.

Worked example: reading the finished project

The project has two files and a way to run each:

File Run with What it shows
guess.py python guess.py the real game, played by a person
test_guess.py python test_guess.py or python -m unittest 7 tests, all passing

Skills practised, with the lesson that taught each:

Skill Where it appears
conditions judge (lesson 5.2)
loops, continue play (lessons 6.1 and 6.3)
exceptions parse_guess and the except in play (chapter 14)
functions and default arguments play(..., low=1, high=100, max_tries=7) (chapter 11)
functions as arguments ask and show (lesson 11.7)
random numbers random.Random().randint (lesson 17.2)
f-strings the messages (lesson 4.5)
tests test_guess.py (chapter 18)

Try this: change max_tries to 6 and run the scripted demo again. A perfect player cannot always win with six tries (the halving needs seven), which you can check by trying secret = 83 in the binary-search loop with the limit applied.

Common mistakes

  • Calling input() and print() inside the logic, which makes it untestable.
  • Counting invalid entries as tries.
  • Forgetting to convert input() text to an integer.
  • Comparing text with numbers ("9" > "10" is true as text).
  • Not validating the range.
  • Picking the secret inside the loop, so it changes each time.
  • Off-by-one errors with range(1, 100) (excludes 100) when picking numbers: randint(1, 100) includes both ends.

Key takeaways

  • A good small project has small functions with one job each, and keeps input and output at the edges.
  • Passing ask and show into the game function makes it testable with scripted answers.
  • Validate input in one place with a clear exception, and let the caller decide what to do.
  • Tests for the boundaries and the failure paths catch most bugs.
  • Binary search shows why seven tries are enough for 100 numbers.

Practice

1. Which function would you change to make the game accept numbers from 1 to 1000?

Show answer

None: call play(secret, input, print, low=1, high=1000, max_tries=10) and pick the secret with randint(1, 1000).

2. Why does parse_guess raise ValueError rather than returning None for bad input?

Show answer

An exception cannot be ignored by accident, carries a message for the player, and lets play handle all kinds of bad input in one except.

3. How would you test that the game handles 7 wrong guesses?

Show answer

Call play with a scripted ask that returns seven wrong numbers, and check that the result is None and the last message contains the secret.

4. Add a "play again?" feature. What changes?

Show answer

Only main: wrap picking a secret and calling play in a while loop that asks input("Again? (y/n) ") and stops on anything but "y".

5. Why are seven tries enough for the numbers 1 to 100?

Show answer

Each guess at the middle halves the remaining range, and 100 halved seven times reaches 1 (2 to the power 7 is 128, which is at least 100).

6. What would you change so the secret is the same on every run, for debugging?

Show answer

Seed the generator: random.Random(12345); the same seed gives the same secret.