Skip to main content
All projects
Python project

Number-guessing game

Instead of typing guesses one at a time, you'll give the game a list of guesses and let it judge each one. Once the rules work, you'll write a computer player that never needs more than seven guesses to find a number from 1 to 100.

Skills you'll practise

  • Functions
  • Conditionals
  • Loops
  • random

Steps

  1. Step 1: Judge one guess

    Finish check_guess(guess, secret) so it returns "Too low", "Too high" or "Correct!".

    Show a hint

    Two if checks are enough. If the guess is neither too low nor too high, it must be correct.

  2. Step 2: Play through a list of guesses

    Loop over the guesses list and print each guess with its result.

    Show a hint

    enumerate(guesses, start=1) gives you the attempt number and the guess together.

  3. Step 3: Stop when it's right

    As soon as a guess is correct, print how many tries it took and leave the loop.

    Show a hint

    return inside a function ends the loop and the function in one go.

  4. Step 4: Limit the tries

    Give the player at most seven guesses. If they run out, reveal the secret number.

  5. Step 5: Let the computer play

    Write a player that always guesses the middle of the range that's left, then narrows the range using the hint. Pick the secret with random.randint(1, 100).

    Show a hint

    Keep low and high. On "Too low", set low = guess + 1; on "Too high", set high = guess - 1.

Starter code

It already runs. The TODO comments mark where to start.

Open in playground
main.py
import random


def check_guess(guess, secret):
    # TODO: return "Too low", "Too high" or "Correct!"
    return "?"


def play(secret, guesses):
    # TODO: loop over the guesses, print each result,
    # and stop as soon as one is correct.
    for guess in guesses:
        print(guess, check_guess(guess, secret))


play(42, [50, 25, 37, 43, 40, 42])

Example solution

One way to finish it. Have a go first; yours doesn't need to match.

Reveal the solution
main.py
import random

MAX_TRIES = 7


def check_guess(guess, secret):
    if guess < secret:
        return "Too low"
    if guess > secret:
        return "Too high"
    return "Correct!"


def play(secret, guesses):
    for attempt, guess in enumerate(guesses, start=1):
        if attempt > MAX_TRIES:
            break
        result = check_guess(guess, secret)
        print(f"Guess {attempt}: {guess} -> {result}")
        if result == "Correct!":
            print(f"Got it in {attempt} tries.")
            return attempt
    print(f"Out of guesses. The number was {secret}.")
    return None


def computer_guesses(secret, low=1, high=100):
    """Always guess the middle of what's left."""
    guesses = []
    while low <= high:
        guess = (low + high) // 2
        guesses.append(guess)
        result = check_guess(guess, secret)
        if result == "Too low":
            low = guess + 1
        elif result == "Too high":
            high = guess - 1
        else:
            break
    return guesses


print("You:")
play(42, [50, 25, 37, 43, 40, 42])

print()
print("The computer:")
secret = random.randint(1, 100)
play(secret, computer_guesses(secret))

Stretch goal

Run the computer player against every number from 1 to 100 and find which secret numbers take the most guesses. Can you explain why it never needs more than seven?

Chapters that help