Project: Number Guessing Game

The plan

Let's build a real program using almost everything you've learned. The computer picks a secret number from 1 to 100, and the player guesses. After each guess the program says too high or too low, until the player wins.

Before writing code, programmers break a problem into small steps:

  1. Pick a secret number.
  2. Ask for a guess, again and again.
  3. If the guess isn't a number, say so and ask again.
  4. Say whether the guess is too high, too low or correct.
  5. When it's correct, say how many tries it took and stop.

Step 1: one guess

Start small. Here the secret number is fixed at 42 so we can test it easily:

secret = 42
guess = int(input("Guess: "))
if guess < secret:
    print("Too low!")
elif guess > secret:
    print("Too high!")
else:
    print("Correct!")

Output (when you type 50)

Guess: 50
Too high!

Step 2: keep guessing

Wrap it in a loop that stops when the guess is right, and count the tries:

secret = 42
tries = 0
while True:
    guess = int(input("Guess: "))
    tries += 1
    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
    else:
        print(f"Correct! You got it in {tries} tries.")
        break

Output (when you type 50, 25, 42)

Guess: 50
Too high!
Guess: 25
Too low!
Guess: 42
Correct! You got it in 3 tries.

Step 3: the finished game

Now we add a random secret number, handle bad input, and put the game in a function so it's easy to play again:

import random

def play(secret):
    tries = 0
    while True:
        try:
            guess = int(input("Guess a number from 1 to 100: "))
        except ValueError:
            print("Please type a whole number.")
            continue
        tries += 1
        if guess < secret:
            print("Too low!")
        elif guess > secret:
            print("Too high!")
        else:
            print(f"Correct! You got it in {tries} tries.")
            return tries

secret = random.randint(1, 100)
secret = 37  # fixed here so the example output is always the same - delete this line to play for real
play(secret)

Output (when you type 50, fifty, 30, 37)

Guess a number from 1 to 100: 50
Too high!
Guess a number from 1 to 100: fifty
Please type a whole number.
Guess a number from 1 to 100: 30
Too low!
Guess a number from 1 to 100: 37
Correct! You got it in 3 tries.

Make it your own

Copy the game into a challenge editor or onto your computer and try adding:

  • A maximum of 7 tries – then reveal the number.
  • Difficulty levels: 1–10, 1–100 or 1–1000.
  • Ask “Play again? (y/n)” at the end and keep a best score.

Tip: This is how real programs are built: start with the smallest thing that works, test it, then add one feature at a time.

HOME LEARN COMMUNITY DASHBOARD