← All video projects

Free video project · Beginner

Build a number guessing game 🎯

The computer picks a secret number from 1 to 100 and you guess until you get it, with a seven guess limit and a check that the player typed a number.

▶ Watch the video

The code from the video

import random

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

while guess != secret and tries < 7:
    answer = input("Guess a number from 1 to 100: ")
    if answer.isdigit():
        guess = int(answer)
        tries += 1
        if guess < secret:
            print("Too low")
        elif guess > secret:
            print("Too high")
    else:
        print("Numbers only, please")

if guess == secret:
    print(f"You got it in {tries} tries!")
else:
    print(f"Out of guesses! It was {secret}")

Run it in your browser with nothing to install, right here on this page.

Make it your own

  1. Let the player choose easy (1 to 50), medium (1 to 100) or hard (1 to 1000) at the start.
  2. Swap the roles: you think of a number and Python guesses it using too high or too low.
  3. Keep a best score and print "New record!" when the player beats it.

Skills: while loops, input, if and elif, random

Start the free lessons More video projects