Project: number guessing game

Mini Projects, lesson 1 of 6

🚀 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".

  1. Judge a guess with a small, testable function
  2. Game loop: keep asking until the guess is right
  3. 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).

Example

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?

Exercise

Step 1: judge a guess

Write check_guess(guess, secret) that returns exactly "too low", "too high" or "correct".

Quiz

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.

Exercise

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 ValueError from int(), print a hint and continue without counting an attempt
  • allow at most max_attempts guesses, then print Out of guesses! It was <secret> and return None

The loop now lives in play(secret, max_attempts=7), which returns the number of attempts used.

Example

Skipping bad input with continue

continue jumps straight to the next round of the loop, skipping everything below it.

Exercise

Step 3: random secret, typos and a limit

Upgrade play and the setup:

  1. Pick secret with random.randint(1, 100) right after random.seed(2024)
  2. On a typo like "fifty", print a hint and continue (no attempt used)
  3. Stop after max_attempts guesses: print Out of guesses! It was <secret> and return None

Your program receives this input: fifty ⏎ 50 ⏎ 75 ⏎ 62 ⏎ 61