Project: Number Guessing Game
Use comparisons, a function, and a loop to evaluate guesses until the answer is found.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
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.
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
secret = 5
guess = 2
if guess < secret:
print("Too low")Too lowThe condition is true because 2 is less than 5.
02. Stop after a match
for guess in [2, 5, 9]:
print(guess)
if guess == 5:
break2
5The loop prints 2 and 5, then break prevents the later guess of 9.
03. Number attempts
for number, guess in enumerate([3, 7], start=1):
print(number, guess)1 3
2 7enumerate 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.
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?
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")Attempt 1: keep trying
Attempt 2: keep trying
Attempt 3: win- enumerate pairs each prepared guess with its one-based attempt number.
- The equality branch prints the win and exits before guess 4.
- Move 6 to the first position and predict the number of printed lines.
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.
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")
breakTry 5 through 20
Try 5 through 13
Found it- Guess 4 excludes 1–4; guess 14 then excludes 14–20.
- The equality branch ends the loop without changing either bound.
- Replace the second guess with 8 and predict the new interval.
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.
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}")Enter a whole number
Choose 1 to 10
Valid attempt 1: 7- continue skips the attempt counter for text and out-of-range values.
- Only the valid 7 is counted as an attempt.
- 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 runNeed input()? Add one value per line
Your output appears here.
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.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Assigning instead of comparing
if guess = secret:
print('Correct')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
if guess < secret:
return 'Too high'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.