LESSON 15 · PRACTICE PROJECT20 min

Project: Number Guessing Game

A guessing game needs three outcomes. A guess below the secret number is too low; one above it is too high; an equal guess is correct. A function can return the matching message, making the decision easy to test.

Use comparisons, a function, and a loop to evaluate guesses until the answer is found.

Before you start: Loops · Functions

Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons

Video lesson: Project: Number Guessing Game

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    Imagine a game with a secret number of seven. The player guesses three, then nine, then seven. A useful game does more than say wrong. It responds too low, too high, and finally correct. In this lesson we will build those three responses in a small function and let a loop process a prepared series of guesses. The result is a complete, repeatable Python project that uses conditions, functions, loops, and break together. Before seeing the code, predict how many attempts the game should print if there is another guess after seven in the list. The answer is three, because the game should stop immediately after the correct guess.

  2. 00:40

    Keep that expected behavior in mind as we construct the program. You can run every example in the browser console on the matching PythonLessonLab lesson page. Start with the decision for one guess. The function receives secret and guess as parameters. If guess is less than secret, return the words too low. If it is greater, return too high. What remains after those two tests? The only remaining relationship is equality, so return correct. This is one way to avoid writing a third comparison that adds no information. Return a message instead of printing inside the function.

  3. 01:20

    That lets another part of the program decide whether to display it, record it, or stop the game. Test the function separately with a secret of seven. A guess of three should return too low. Nine should return too high. Seven should return correct. These three tests cover the three meaningful branches. Now create a list of guesses: three, nine, seven, and eight. We deliberately include eight after the winning guess to test whether the game really stops. A for loop visits the list in order. Enumerate adds an attempt number, starting at one so the message looks natural to a player. On the first pass, attempt is one and guess is three.

  4. 02:02

    The function returns too low, and the loop prints attempt one, too low. On the second pass, nine is too high. On the third pass, seven is correct. The program prints that message, checks the result, and executes break. Break exits the nearest loop immediately, so eight is never examined. Without break, the game would keep playing after a win and print another hint. The completed code in the lesson shows this sequence. Notice that the function handles a single comparison, while the loop handles a whole round. That division of responsibility makes each part easier to change. The browser task uses prepared guesses because it needs a deterministic result for the learner and the checker.

  5. 02:46

    Later, an interactive version could ask for input, convert the returned text to an integer, and feed the integer to the same comparison function. That conversion needs validation because typing a word instead of a number raises an error. The deeper guide on the website shows a sequence containing the word five, an out-of-range zero, and a valid seven. It reports the two invalid entries without counting them as attempts. Decide whether bad entries count before you implement a real game; either choice can work if the rule is clear. Hints can also narrow the search interval. Suppose the secret is between one and twenty.

  6. 03:26

    A guess of four that is too low rules out one through four. The lowest remaining possibility is five. If fourteen is too high, the highest remaining possibility is thirteen. Keeping a lower and upper bound makes these deductions visible and can help a player choose the next guess. After a low guess, set the lower bound to guess plus one. After a high guess, set the upper bound to guess minus one. The plus or minus one matters because the rejected guess cannot still be a candidate. Try the guide example with four, fourteen, and ten, and predict the displayed intervals before running it. These extras are not needed to pass the beginner task, but they show how a tiny guessing game can develop into a more complete program.

  7. 04:12

    A wrong comparison can be more dangerous than a crash because it produces convincing but false feedback. If the less-than branch returns too high, a guess of three against seven misdirects the player. Trace that one call and compare the numbers before trusting the message. Another mistake is to print correct and forget break. The next guess then runs even though the round is finished. Include a value after the secret in the prepared list specifically to reveal that bug. A third mistake is assuming input gives an integer. The input function returns text, so comparing its result directly with numeric secret is invalid.

  8. 04:53

    Convert it with int, catch a possible ValueError, and reject numbers outside the chosen range before spending an attempt. In the starter exercise, prepared integer guesses let you focus on the main game logic first. Your task is to finish the check guess function with the three exact return messages. Predict the output for three, nine, seven, and eight before pressing Run. You should see three lines, with no fourth attempt after correct. Next try moving seven to the first position. The game should print one line and stop. Then move it to the last position and predict how many hints come first. Use the task checker after these manual tests.

  9. 05:36

    It checks different secret and guess values, so a function that only works for seven will not pass. Complete the three-question quiz to mark the lesson done. For an optional extension, track a lower and upper bound or add input validation using the deeper guide examples. This separation between a decision function, game loop, and input handling is useful far beyond games. It is the same pattern you might use for a form that validates one entry while a larger workflow decides what happens next. The on-screen link opens the full lesson with console, worked examples, mistakes, and hints.

Understand the concept

The starter runs a prepared list of guesses so the result is repeatable in the browser. The loop prints each attempt and stops with break when the function returns Correct. After the checked task, you can change the list or replace it with input() for interactive play.

Keeping the secret fixed while learning makes debugging easier. A later variation can choose a random secret, but then an example's exact output depends on the random result.

  • Compare with <, >, and ==
  • Return one of three outcomes
  • break exits a loop after a correct guess

See it step by step

Read the code, predict the output, then compare it with the result.

01. Compare a guess

PYTHON
secret = 5
guess = 2
if guess < secret:
    print("Too low")
EXPECTED OUTPUT
Too low

The condition is true because 2 is less than 5.

02. Stop after a match

PYTHON
for guess in [2, 5, 9]:
    print(guess)
    if guess == 5:
        break
EXPECTED OUTPUT
2
5

The loop prints 2 and 5, then break prevents the later guess of 9.

03. Number attempts

PYTHON
for number, guess in enumerate([3, 7], start=1):
    print(number, guess)
EXPECTED OUTPUT
1 3
2 7

enumerate pairs each item with a count beginning at one.

A closer look

Follow the reasoning, inspect each result, then try the suggested changes in the console below.

01 / 03

Model the game as changing state

A game is easier to reason about when you list the facts that can change: the secret stays fixed, the current guess changes, and the attempt count increases. The game ends when the guess matches the secret or when the attempt limit is reached. A function that evaluates one guess and a loop that controls the whole game have different jobs. Keeping them separate lets you check the decision rules without playing an entire game.

The browser lesson uses prepared guesses to make the output repeatable. The same loop could later receive guesses from a human, but input() would wait for input and is awkward for an automatically checked example. Trace the list below by hand: which guesses are visited, what is the attempt count at each one, and why is the last item never printed?

PYTHON
secret = 6
guesses = [2, 8, 6, 4]
for attempt, guess in enumerate(guesses, start=1):
    if guess == secret:
        print(f"Attempt {attempt}: win")
        break
    print(f"Attempt {attempt}: keep trying")
EXPECTED OUTPUT
Attempt 1: keep trying
Attempt 2: keep trying
Attempt 3: win
Follow the reasoning
  1. enumerate pairs each prepared guess with its one-based attempt number.
  2. The equality branch prints the win and exits before guess 4.
  3. Move 6 to the first position and predict the number of printed lines.
02 / 03

Use hints to narrow the search

A low or high hint is information about an entire interval, not just one guess. If the secret is between 1 and 20 and 4 is too low, every number from 1 through 4 is ruled out. If 14 is too high, every number from 14 through 20 is ruled out. Keeping lower and upper bounds makes this reasoning visible to the player.

The bounds here are inclusive. After a low guess, the new minimum is guess + 1; after a high guess, the new maximum is guess - 1. Forgetting the plus or minus one leaves a value that has already been rejected in the range. With a real player, you could display the updated interval after each turn.

PYTHON
low, high = 1, 20
secret = 10
for guess in [4, 14, 10]:
    if guess < secret:
        low = guess + 1
        print(f"Try {low} through {high}")
    elif guess > secret:
        high = guess - 1
        print(f"Try {low} through {high}")
    else:
        print("Found it")
        break
EXPECTED OUTPUT
Try 5 through 20
Try 5 through 13
Found it
Follow the reasoning
  1. Guess 4 excludes 1–4; guess 14 then excludes 14–20.
  2. The equality branch ends the loop without changing either bound.
  3. Replace the second guess with 8 and predict the new interval.
03 / 03

Keep bad entries from costing a turn

Human input arrives as text, even when a person intended a number. int('five') raises ValueError, and a number outside the game range should also be rejected. Decide whether an invalid entry counts as an attempt before you write the loop. In this example, invalid entries are reported but do not increase the count. That policy makes the attempt limit fair and testable.

Separating parsing from the game rule prevents a bad entry from reaching the comparison logic. The sample uses a fixed list of strings so you can run it without an input prompt. A full game could repeatedly ask for text, parse it, and only then spend an attempt. The same approach applies to forms and command-line tools.

PYTHON
entries = ["five", "0", "7"]
attempts = 0
for entry in entries:
    try:
        guess = int(entry)
    except ValueError:
        print("Enter a whole number")
        continue
    if not 1 <= guess <= 10:
        print("Choose 1 to 10")
        continue
    attempts += 1
    print(f"Valid attempt {attempts}: {guess}")
EXPECTED OUTPUT
Enter a whole number
Choose 1 to 10
Valid attempt 1: 7
Follow the reasoning
  1. continue skips the attempt counter for text and out-of-range values.
  2. Only the valid 7 is counted as an attempt.
  3. Add '11' to entries and predict whether the count changes.

Try it in Python

Edit the example and run it. Python starts in your browser the first time you click Run.

Python console

Ready to run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnFinish check_guess(secret, guess) so it returns exactly Too low, Too high, or Correct. Run the prepared guesses and make the final line Attempt 3: Correct. The game should stop after a correct answer.
Need a hint?

Use if guess < secret, elif guess > secret, and else. Return the specified strings without extra punctuation. The existing loop already stops on Correct.

Complete the task and select Check task to verify your code.

    Quick quiz

    Three questions. You can change your answers and try again.

    01.Which comparison tests whether a guess matches the secret?

    02.What does break do in the game loop?

    03.For secret 7 and guess 9, which message is correct?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Assigning instead of comparing

    COMMON MISTAKE
    if guess = secret:
        print('Correct')
    FIX
    if guess == secret:
        print('Correct')

    What happens: SyntaxError because = is assignment, not comparison.
    Use == when asking whether two values are equal.

    Reversing the low hint

    COMMON MISTAKE
    if guess < secret:
        return 'Too high'
    FIX
    if guess < secret:
        return 'Too low'

    What happens: The player receives a misleading hint.
    Compare the guessed number to the secret from the player's perspective.

    Browse this lesson’s problem fixes

    Sources and further reading