🚀 Mini Projects, lesson 1 of 6
Project: number guessing game
Build a complete game: judge guesses, loop, then add randomness and typo handling.
12 min
3 exercises
1 quiz
0/4 solved
Getting Python ready… examples can run in a moment.
Time to build a real program: the classic guess the number game. The computer picks a secret from 1 to 100 and answers each guess with "too low" or "too high".
- Judge a guess with a small, testable function
- Game loop: keep asking until the guess is right
- Polish: a random secret, a guess limit and protection against typos
Each step is an exercise that starts from the previous
step's code. Games need input, so exercises come with
pre-filled input lines (one per input() call).
Preview: the finished basics
One line per input() call
The input box holds the guesses 50, 60, 55 and 52. Change them (one per line) to play differently. What happens if you run out of guesses?
Step 1: judge a guess
Write check_guess(guess, secret) that returns
exactly "too low", "too high" or "correct".
What does this print?
Step 2: the game loop. while True: keeps asking
and break ends the loop once the guess is right.
Count every guess in attempts. Keep the secret fixed
at 42 for now, so the pre-filled guesses (50, 25, 42)
always play out the same way.
Step 2: the game loop
Write the loop: read a guess with
int(input("Guess 1-100: ")), add 1 to attempts,
print the result of check_guess, and stop when it's
"correct". The last line prints the score.
Your program receives this input: 50 ⏎ 25 ⏎ 42
Step 3: polish. Real players make typos, and the secret must be random:
- pick the secret with
random.randint(1, 100)(seeded, so the check can replay the game) - catch the
ValueErrorfromint(), print a hint andcontinuewithout counting an attempt - allow at most
max_attemptsguesses, then printOut of guesses! It was <secret>and returnNone
The loop now lives in play(secret, max_attempts=7),
which returns the number of attempts used.
Skipping bad input with continue
continue jumps straight to the next round of the
loop, skipping everything below it.
Step 3: random secret, typos and a limit
Upgrade play and the setup:
- Pick
secretwithrandom.randint(1, 100)right afterrandom.seed(2024) - On a typo like "fifty", print a hint and
continue(no attempt used) - Stop after
max_attemptsguesses: printOut of guesses! It was <secret>and returnNone
Your program receives this input: fifty ⏎ 50 ⏎ 75 ⏎ 62 ⏎ 61