Part 4 mini-project: Number Guessing Game

This project combines every idea from Parts 3 and 4: variables, input, comparisons, branching, looping. The result is a small but truly interactive game.

What to build

A program that, when run:

  1. Picks a random whole number from 1 to 100 (the target), hidden from the user.
  2. Repeatedly:
    • Prompts the user for a guess.
    • Reads the guess.
    • Prints Too low., Too high., or Correct! based on how the guess compares to the target.
    • Counts attempts.
  3. When the guess matches, prints how many attempts it took, then stops.

A typical session:

I am thinking of a number between 1 and 100.
Guess: 50
Too high.
Guess: 25
Too low.
Guess: 37
Too high.
Guess: 31
Too low.
Guess: 34
Correct! You got it in 5 attempts.

Files

Starter and finished versions are in projects/03-number-guess/:

  • starter.py — scaffolding with TODO comments.
  • finished.py — a working version. Compare yours afterwards.

Run with:

python projects/03-number-guess/starter.py

Hints

  • import random at the top of the file, then random.randint(1, 100) picks the target. Call it once, before the loop. Inside the loop, the target stays the same.
  • A while True: loop with a break fits well: the body asks once, then an if guess == target: check breaks out when the player wins.
  • An attempts counter is a variable set to 0 before the loop and bumped by 1 inside the body.
  • The guess arrives as text from input(). Wrap it with int() before comparing, e.g. guess = int(input("Guess: ")).

What you cannot use yet

  • Lists. No need to store a guess history.
  • Functions of your own. The game fits in one straight script.

A bigger challenge (optional)

If the basic version works, try one of these:

  • After three wrong guesses, print a hint saying whether the target is even or odd.
  • Track the highest and lowest guess so far, and print the bracket each round, like (known range: 32 to 49).

Neither is required to consider the project finished.

Done?

When the game runs cleanly start to finish — chooses a target, takes guesses, gives feedback, ends with the attempts count — Part 4 is done. Move on to Chapter 21 — Functions.