Python Tutorial
Python Project: Guess the Number
A guessing game that picks a secret integer, counts attempts, and gives high/low hints until you win.
What you are building
You build a small game. The program holds a secret integer from 1 to 20. Each guess is compared to that secret. The player hears too high, too low, or correct. When the match happens, the program prints how many attempts it took.
Copy every example into the Python editor at /try and click Run. That editor is Python only. It is not HTML, C, or C++. The complete program uses a list of guesses so it prints a full playthrough without waiting for input().
Skills used
if/elif/elseto compare a guess to the secret- A
forloop over a list of demo guesses - A counter that goes up on every attempt
random.randintwhen you later want a new secret each runbreakto stop as soon as the player wins
Compare one guess
Start with three numbers: a low bound, a high bound, and a secret. Then test a single guess. The comparison is the whole game in miniature.
Example
secret = 12
guess = 10
print("Secret is between 1 and 20.")
print("Guess:", guess)
if guess < secret:
print("Too low.")
elif guess > secret:
print("Too high.")
else:
print("Correct.")Change guess to 15, then to 12. You should see too high, then correct. That is the hint table the rest of the program will print on every attempt.
| Guess vs secret | Message |
|---|---|
| guess is smaller | Too low |
| guess is larger | Too high |
| guess equals secret | Correct |
Drive the game from a list
In a terminal you would call input() inside a loop. In the browser editor, a stuck prompt is a bad demo. Put the guesses in a list and loop over them. Count every pass. Stop with break when the secret is found.
Example
secret = 12
guesses = [10, 15, 12]
attempts = 0
for guess in guesses:
attempts += 1
print("Attempt", attempts, "->", guess)
if guess == secret:
print("Hit.")
break
if guess < secret:
print("Too low.")
else:
print("Too high.")
print("Attempts used:", attempts)Keep the secret in a variable, not copied into every if. Then one change ofsecret updates the whole game. A live version can set that variable withrandom.randint(1, 20) after import random.
Complete program
This is the full game. The secret is 12 so the demo list [10, 15, 12] wins on the third try. Run it at /try. You should see two hints, then a win line with the attempt count.
Example
LOW = 1
HIGH = 20
SECRET = 12
GUESSES = [10, 15, 12]
print("Guess the number.")
print("Range:", LOW, "to", HIGH)
attempts = 0
won = False
for guess in GUESSES:
attempts += 1
print()
print("Attempt", attempts, ":", guess)
if guess < LOW or guess > HIGH:
print("Out of range. Stay between", LOW, "and", HIGH, ".")
continue
if guess < SECRET:
print("Too low.")
elif guess > SECRET:
print("Too high.")
else:
print("Correct! The number was", SECRET)
won = True
break
print()
if won:
print("You won in", attempts, "attempts.")
else:
print("No more guesses. The number was", SECRET)The range check is extra, not required for this demo list. It shows how you reject a value without counting it as a win. continue skips the rest of that loop pass and moves to the next guess.
Optional: type guesses with input
After the list version works, you can swap the list for input(). Run this only when you are ready to type. The browser editor will wait until you enter a line.
Example
# Optional interactive variant. The complete program above does not need this.
secret = 12
attempts = 0
while True:
attempts += 1
guess = int(input("Guess: "))
if guess == secret:
print("Correct in", attempts, "tries.")
break
if guess < secret:
print("Too low.")
else:
print("Too high.")Common mistakes
- Using
input()as the only path, then wondering why Run sits still. Demo with a list first. - Comparing strings to integers.
input()returns text. Wrap it withint(...)if you switch to typing. - Forgetting
break. The loop then keeps printing after the player already won. - Resetting
attemptsinside the loop. The counter must live outside so it survives each pass. - Calling
random.randintwithout a seed in a tutorial screenshot. The secret then changes every run and the written guesses no longer match. Fix the secret for demos.
How to extend / Practice tasks
Make three concrete changes. Run after each one.
- Set
SECRET = 7and changeGUESSESto[5, 9, 7]. Confirm the hints flip from too low to too high to correct. - Widen the range to 1 through 50. Add a fourth guess that is 51 and check that the out-of-range branch prints.
- Track the best (lowest) attempt count across two playthroughs in the same file: run the loop twice with two different guess lists and print which list won faster.
📘 Real-World Deep Dive
The number-guessing game is the smallest complete program with a real game loop: hidden state, repeated input, a narrowing hint, and a win condition. Every larger game is this skeleton with more flesh.
What to build
The computer picks 1–100; the player guesses; each guess prints higher/lower; the game ends on a correct guess and reports the attempt count.
Real-Life Example
import random
def play(secret: int, guesses: list[int]) -> str:
for turn, g in enumerate(guesses, 1):
if g == secret:
return f"correct in {turn} tries"
print("higher" if g < secret else "lower")
return "out of guesses"
# Deterministic for the demo; use random.randint(1, 100) live.
print(play(secret=42, guesses=[50, 25, 37, 43, 42]))Passing guesses in as a list (instead of calling input()) makes the game logic testable without a keyboard.
Expected Output
lower
higher
higher
lower
correct in 5 triesCommon mistakes
input()returns a string — forgettingint(...)makes every comparison wrong. Validate and re-prompt on non-numbers.- An unbounded
while Truewith no attempt cap can loop forever in a test. Give the game a max number of tries. - Calling
random.randintinside the guessing loop re-rolls the secret every turn — set it once before the loop.
🚀 Performance & Best Practices
- Optimal play is binary search: the answer is always findable in ⌈log₂100⌉ = 7 guesses. Great follow-up discussion.
- Separate the pure game logic from I/O (as above) so you can unit-test wins, losses, and edge guesses.
- Seed
random.Random(seed)in tests for reproducible runs.
🧪 Try It Yourself
- Add difficulty levels that change the range (1–10, 1–100, 1–1000) and the allowed number of guesses.
- Track a best score (fewest guesses) across rounds in the same session.
- Have the computer guess your number using binary search and count its tries.