🚀 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 the input lines run out before you find the secret?
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. Put the loop inside a
function play(secret) so it can be replayed with
any guesses. while True: keeps asking and return
ends the game once the guess is right. Count every
guess in attempts and return it. 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
Finish play(secret): read a guess with
int(input("Guess 1-100: ")), add 1 to attempts,
print the result of check_guess, and when it's
"correct" return attempts. The check replays
your function with several guess sequences, so the
loop has to be real.
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
Your play from step 2 gains a
max_attempts=7 parameter and still 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