Syllabus: Mini Projects
1.1 Free

Number guessing game

A game that picks a number and helps you find it.

What you will build

A game where the computer picks a secret number between 1 and 20 and you try to guess it. After each guess the program says too high, too low or correct, and counts your guesses.

The plan

  1. 1Pick a random whole number from 1 to 20.
  2. 2Ask the player for a guess.
  3. 3Compare the guess with the secret number and give a hint.
  4. 4Repeat until the guess is right, counting each try.
  5. 5Print how many guesses it took.

Starter code

import random

secret = random.randint(1, 20)
tries = 0
guess = 0

while guess != secret:
    guess = int(input("Guess the number (1-20): "))
    tries = tries + 1
    if guess < secret:
        print("Too low")
    elif guess > secret:
        print("Too high")

print("Correct! You needed", tries, "guesses.")

Level up

  1. 1Stop after 6 guesses and reveal the number.
  2. 2Ask whether the player wants to play again.
  3. 3Let the player choose the range.