blog / guides

build a Python number guessing game, step by step

by Luke published 9 min read

the short answer

A number guessing game needs five pieces: random.randint picks a secret number, input asks for a guess, int turns the answer into a number, if, elif and else say too high, too low or correct, and a while loop keeps asking until the guess is right. Add a counter for the number of tries and you have a complete game in about 20 lines.

A number guessing game is one of the best first projects in Python. The computer picks a secret number, you guess, and it tells you whether to go higher or lower until you get it. It is small enough to finish in one sitting, and it uses the ideas every program needs: variables, input, decisions and a loop.

Here is a game in progress:

I'm thinking of a number from 1 to 100.
Your guess: 50
Too high!
Your guess: 25
Too low!
Your guess: fifty
Please type a whole number.
Your guess: 37
You got it in 3 tries!

This tutorial builds that game one piece at a time, running each piece as you go. At the end you get the full program to play on your own computer, plus ideas for making it your own.

Step 1: pick a secret number

Python’s random module can pick numbers for you. random.randint(1, 100) gives a whole number from 1 to 100, and both ends can come up:

try it · python
import random

secret = random.randint(1, 100)
print(secret)

Run it a few times. You should see a different number between 1 and 100 most times. The import random line has to come first, because without it Python does not know the name random. The module has other handy tools too: random.choice picks one item from a list, which would suit a word guessing game later.

While we build the rest of the game, we will fix the secret at 37. That way every run box below gives the same output, and you can check yours against it. The random line goes back in for the final game.

Step 2: compare one guess

The heart of the game is a three-way decision: too high, too low or correct. if, elif and else handle it:

try it · python
secret = 37
guess = 50

if guess > secret:
    print("Too high!")
elif guess < secret:
    print("Too low!")
else:
    print("You got it!")
Too high!

Python checks each test in order and runs the first one that is true. If neither test is true, the guess must be equal, so the else branch runs. Change guess to 20 or 37 to see the other answers.

Step 3: turn typed text into a number

input always hands back text, even when the player types digits. int turns that text into a number you can do maths and comparisons with:

try it · python
text = "50"
guess = int(text)
print(guess + 1)
51

But int cannot turn a word into a number:

try it · python
guess = int("fifty")
  File "<exec>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'fifty'

A real player will type something odd sooner or later, so the game should check first. isdigit() is True only when every character is a digit:

try it · python
print("50".isdigit())
print("fifty".isdigit())
print("".isdigit())
print("-5".isdigit())
True
False
False
False

An empty answer and a minus sign both count as not a number, which suits this game, where the secret is always 1 or more.

A pretend player for the run boxes

The run boxes on this page cannot read the keyboard, so input stops with an EOFError here. To test the game anyway, we will use a pretend player. This small function, ask, works like input, except that it takes its answers from a list and prints them as if someone had typed them:

try it · python
typed = ["50", "25", "fifty", "37"]

def ask(question):
    answer = typed.pop(0)
    print(question + answer)
    return answer

name = ask("Your guess: ")
print("You typed " + name)
Your guess: 50
You typed 50

typed.pop(0) takes the first answer off the front of the list, so each call gets the next one. Testing with fixed answers like this is a trick real programmers use too, because it makes every run the same.

Step 4: keep asking with a loop

Now put the pieces inside a loop. while True: repeats forever, continue skips back to the top for another go, and break leaves the loop when the guess is right. A counter keeps track of the tries:

try it · python
typed = ["50", "25", "fifty", "37"]

def ask(question):
    answer = typed.pop(0)
    print(question + answer)
    return answer

secret = 37
tries = 0

print("I'm thinking of a number from 1 to 100.")

while True:
    text = ask("Your guess: ")
    if not text.isdigit():
        print("Please type a whole number.")
        continue
    guess = int(text)
    tries = tries + 1
    if guess > secret:
        print("Too high!")
    elif guess < secret:
        print("Too low!")
    else:
        print(f"You got it in {tries} tries!")
        break
I'm thinking of a number from 1 to 100.
Your guess: 50
Too high!
Your guess: 25
Too low!
Your guess: fifty
Please type a whole number.
Your guess: 37
You got it in 3 tries!

That is the whole game. Notice that tries = tries + 1 comes after the isdigit check, so typing a word does not use up a try. The f before the last string makes it an f-string, which puts the value of tries inside the text.

The finished game

Swap the pretend player for the real input, and the fixed 37 for a random number:

import random

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

print("I'm thinking of a number from 1 to 100.")

while True:
    text = input("Your guess: ")
    if not text.isdigit():
        print("Please type a whole number.")
        continue
    guess = int(text)
    tries = tries + 1
    if guess > secret:
        print("Too high!")
    elif guess < secret:
        print("Too low!")
    else:
        print(f"You got it in {tries} tries!")
        break

To play it, install Python on your computer, save the code in a file called guess.py, and run python guess.py in a terminal. On Windows, py guess.py also works. We played this exact file through to a win before publishing.

Common mistakes

Forgetting int

try it · python
secret = 37
guess = "50"
if guess > secret:
    print("Too high!")
  File "<exec>", line 3, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'

Python will not compare text with a number. Wrap the answer in int before comparing.

One equals sign in a test

try it · python
secret = 37
guess = 37
if guess = secret:
    print("You got it!")
  File "<exec>", line 3
    if guess = secret:
       ^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

One = puts a value in a variable. Two, ==, asks whether two values are the same.

Picking the secret inside the loop

If secret = random.randint(1, 100) sits inside the while loop, the number changes after every guess, and too high or too low stops meaning anything. Pick it once, before the loop starts.

A loop with no way out

Without break, a while True: loop never ends, even after the right guess. If your game keeps asking after a win, check that break is inside the else branch.

Counting tries in the wrong place

Put tries = tries + 1 before the isdigit check and a typed word costs the player a try. Count only real guesses.

Make it your own

  • Say “1 try” instead of “1 tries” when someone wins first time.
  • Let the player choose the range, such as 1 to 10 for a quick game.
  • Ask “Play again?” at the end and start a new round if they type yes.
  • Limit the number of guesses, which is the exercise below.

A short exercise

Change the game so the player has only 7 guesses. If they run out, print Out of guesses! It was 37. Keep the pretend player so you can test it, using seven wrong answers. Try it in the playground from the button at the bottom of the page, choosing Python.

One possible answer

try it · python
typed = ["50", "25", "30", "33", "35", "36", "40"]

def ask(question):
    answer = typed.pop(0)
    print(question + answer)
    return answer

secret = 37
tries = 0

while tries < 7:
    guess = int(ask("Your guess: "))
    tries = tries + 1
    if guess > secret:
        print("Too high!")
    elif guess < secret:
        print("Too low!")
    else:
        print(f"You got it in {tries} tries!")
        break

if guess != secret:
    print(f"Out of guesses! It was {secret}.")
Your guess: 50
Too high!
Your guess: 25
Too low!
Your guess: 30
Too low!
Your guess: 33
Too low!
Your guess: 35
Too low!
Your guess: 36
Too low!
Your guess: 40
Too high!
Out of guesses! It was 37.

The loop now stops after 7 tries on its own. After the loop, the last guess tells you whether the player won. To keep this answer short, it leaves out the isdigit check. Put it back in before you play the real version.

Your next step

Finishing a game you can actually play is a great feeling, and every idea in it comes from Python’s basics. Gwecode’s Python Level 1 teaches each one in its own short lesson, including asking a question with input, repeating with while and stopping early with break. Its level check is a tiny quiz game you build yourself, a good next project after this one. Every lesson is free and runs in your browser. Create a free account to keep your progress, and start with the lesson below.

practise this · python · lessonAsking a questionstart the lesson

questions

How do I make Python pick a random number?

Import the random module, then call random.randint(1, 100). It returns a whole number from 1 to 100, and both ends can be picked.

Why do I need int() around input()?

input always gives back text, even when someone types digits. int turns that text into a number, so you can compare it with the secret number using < and >.

How do I stop the game crashing when someone types a word?

Check the text before converting it. text.isdigit() is True only when every character is a digit, so you can print a message and ask again when it is False.

How do I limit the number of guesses?

Loop while the tries are below the limit, for example while tries < 7. After the loop, check whether the last guess was right and, if not, reveal the number.

Why is the run box version different from the final game?

Run boxes on the blog cannot read the keyboard, so the step-by-step boxes use a pretend player that types answers from a list. The final game uses the real input and runs on your own computer.

keep going.