Skip to main content

Programming fundamentals · Beginner · 20 min

Build a number guessing game in Python

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will build a playable command-line game where the computer picks a secret number and gives higher and lower hints, with input checks, difficulty levels, a play-again loop, a seeded replay mode and two tests.

On this page

A number guessing game is small enough to finish in one sitting and big enough to use most of what you learn in your first weeks of programming: a random number, a loop, decisions with if, checking what the user types, a dictionary of settings, and functions. It is a good first project because you can play it the moment each step is done and feel whether the change worked.

You build the game in seven steps. Each step replaces game.py with a slightly bigger version, so you can always compare your file with the one shown. First the computer picks a number and you get one guess. Then you get as many guesses as you need, then the game stops crashing on bad input, then it gets difficulty levels and a guess limit, then a "play again" question. Finally you reorganise it into functions, add a way to replay the exact same game with a seed, and write two tests.

The commands use python3. On Windows outside WSL, type py instead. On an Android phone, the Termux app can install Python with pkg install python; the game runs entirely offline, so it costs no mobile data once Python is installed.

Step 1 · Pick a secret number and take one guess

Make a folder for the project and write the first version of the game:

Bash
mkdir -p ~/guessing-demo
cd ~/guessing-demo
cat > game.py <<'PY'
import random

secret = random.randint(1, 100)
guess = int(input("Guess a number from 1 to 100: "))

if guess < secret:
    print("Higher")
elif guess > secret:
    print("Lower")
else:
    print("Correct")

print("The number was", secret)
PY

You can also type the lines between the two PY markers into your editor and save them as game.py. Line by line:

  • import random loads Python's built-in random module. Nothing needs installing.
  • random.randint(1, 100) returns a whole number from 1 to 100. Both ends are included, so 1 and 100 can both come up. The result is stored in secret.
  • input(...) shows the prompt and waits for you to type something and press Enter. It always gives back text, even if you type digits, so int(...) turns that text into a whole number.
  • The if/elif/else block compares the two numbers. Exactly one of the three branches runs: if your guess is too small the hint is Higher, too big gives Lower, and anything else must be equal.
  • The last line is not indented, so it runs after the comparison whichever branch was taken.

Run it and type 50:

Bash
python3 game.py

Check it worked

You see one of Higher, Lower or Correct, then a line such as The number was 73. Run it a few more times: the number changes each time, and the hint always matches it (if the number was 73, a guess of 50 said Higher).

Step 2 · Keep guessing until you get it

One guess is not much of a game. Wrap the guessing in a loop that repeats until the guess is right, and count the guesses as you go:

Bash
cat > game.py <<'PY'
import random

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

while True:
    guess = int(input("Your guess: "))
    guesses = guesses + 1

    if guess < secret:
        print("Higher")
    elif guess > secret:
        print("Lower")
    else:
        print(f"Correct. You took {guesses} guesses.")
        break
PY

What changed:

  • guesses = 0 starts a counter before the loop. It has to be outside the loop, or it would go back to 0 on every guess.
  • while True: starts a loop whose condition is always true, so on its own it would never stop. The way out is break, further down.
  • Everything indented under while True: is the loop body and runs once per guess.
  • guesses = guesses + 1 adds one to the counter each time round.
  • In the else branch, break leaves the loop at once. Since nothing comes after the loop, the program ends.
  • The f before the quotes makes an f-string: {guesses} is replaced by the counter's value.

Play a round:

Bash
python3 game.py

A good strategy is to halve the range each time: start at 50, then 25 or 75, and so on. Halving means you never need more than seven guesses for 1 to 100, because seven halvings shrink 100 numbers down to one. You will use that fact for the difficulty levels later.

Check it worked

The game keeps asking Your guess: and answering Higher or Lower until you hit the number, then prints a line such as Correct. You took 6 guesses. and your prompt comes back.

Step 3 · Stop bad input from crashing the game

Run the game and type ten instead of a number. The program stops with a traceback ending in ValueError: invalid literal for int() with base 10: 'ten'. int() cannot turn that text into a number, so it raises an error, and nothing in the program handles it. Typing 500 is also wrong but slips through, because nothing checks the range.

Fix both. Catch the error with try and except, and check the range with if:

Bash
cat > game.py <<'PY'
import random

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

while True:
    text = input("Your guess: ")
    try:
        guess = int(text)
    except ValueError:
        print(f"{text!r} is not a whole number. Try again.")
        continue

    if guess < 1 or guess > 100:
        print("Pick a number from 1 to 100.")
        continue

    guesses = guesses + 1

    if guess < secret:
        print("Higher")
    elif guess > secret:
        print("Lower")
    else:
        print(f"Correct. You took {guesses} guesses.")
        break
PY

How the new lines work:

  • text = input(...) keeps what was typed as text, so the error message can show it.
  • try: marks code that might fail. If int(text) raises ValueError, Python jumps straight to the matching except ValueError: block instead of crashing.
  • {text!r} shows the text with quotes around it, so an empty entry shows as '' rather than nothing.
  • continue skips the rest of the loop body and goes back to the top for the next guess. The counter line comes after both checks, so a bad entry does not cost the player a guess.
  • guess < 1 or guess > 100 is true when the number is below 1 or above 100. Either one is enough.

int() ignores spaces around the digits, so 42 ` is accepted. It rejects `4.5 and 4,000, which is what you want for whole numbers.

Bash
python3 game.py

Check it worked

Type ten: the game prints 'ten' is not a whole number. Try again. and asks again. Type 0: it prints Pick a number from 1 to 100. Press Enter on an empty line: it prints '' is not a whole number. Try again. Then win the round: the guess count at the end includes only real guesses.

Step 4 · Add difficulty levels with a dictionary

Make the game ask for a level, and give each level its own range and guess limit. A dictionary is a good fit: each level name is a key, and its value holds the settings for that level.

Bash
cat > game.py <<'PY'
import random

LEVELS = {
    "easy": {"top": 10, "tries": 5},
    "normal": {"top": 50, "tries": 7},
    "hard": {"top": 100, "tries": 7},
}

level = input("Level (easy, normal, hard): ").strip().lower()
while level not in LEVELS:
    level = input("Type easy, normal or hard: ").strip().lower()

top = LEVELS[level]["top"]
tries = LEVELS[level]["tries"]
secret = random.randint(1, top)
guesses = 0
won = False

while guesses < tries:
    text = input(f"Guess a number from 1 to {top}: ")
    try:
        guess = int(text)
    except ValueError:
        print(f"{text!r} is not a whole number. Try again.")
        continue

    if guess < 1 or guess > top:
        print(f"Pick a number from 1 to {top}.")
        continue

    guesses = guesses + 1

    if guess < secret:
        print(f"Higher. {tries - guesses} left.")
    elif guess > secret:
        print(f"Lower. {tries - guesses} left.")
    else:
        won = True
        break

if won:
    print(f"Correct. You took {guesses} of {tries} guesses.")
else:
    print(f"Out of guesses. The number was {secret}.")
PY

The new parts:

  • LEVELS is a dictionary of dictionaries. LEVELS["hard"] is {"top": 100, "tries": 7}, and LEVELS["hard"]["top"] is 100. The name is in capitals by convention, to say "this is a setting, the program does not change it". To add a level, you add one line here and nothing else.
  • .strip() removes spaces around the answer and .lower() makes it lower case, so Easy and ` EASY ` both work.
  • level not in LEVELS is true when the answer is not one of the dictionary's keys. The small while loop keeps asking until it is.
  • while guesses < tries: replaces while True:. The loop now also ends when the player runs out of guesses.
  • won starts as False and becomes True only on a correct guess. After the loop, it tells you which of the two ways the loop ended, so the right message is printed.
  • Hard gives 7 guesses for 100 numbers: exactly enough if you halve the range every time, and not enough if you guess at random.

Play once on easy, then once on hard:

Bash
python3 game.py

Check it worked

Type medium at the first question: the game answers Type easy, normal or hard:. On easy, the prompt says Guess a number from 1 to 10: and every hint ends with how many guesses remain, such as Higher. 4 left. Win and you see Correct. You took 3 of 5 guesses. (your count will vary). Lose on purpose by typing the same wrong number five times, and you see a line such as Out of guesses. The number was 8..

Step 5 · Ask to play again

To offer another round, put everything from the level question to the result message inside a second loop, and ask a question at the end:

Bash
cat > game.py <<'PY'
import random

LEVELS = {
    "easy": {"top": 10, "tries": 5},
    "normal": {"top": 50, "tries": 7},
    "hard": {"top": 100, "tries": 7},
}

while True:
    level = input("Level (easy, normal, hard): ").strip().lower()
    while level not in LEVELS:
        level = input("Type easy, normal or hard: ").strip().lower()

    top = LEVELS[level]["top"]
    tries = LEVELS[level]["tries"]
    secret = random.randint(1, top)
    guesses = 0
    won = False

    while guesses < tries:
        text = input(f"Guess a number from 1 to {top}: ")
        try:
            guess = int(text)
        except ValueError:
            print(f"{text!r} is not a whole number. Try again.")
            continue

        if guess < 1 or guess > top:
            print(f"Pick a number from 1 to {top}.")
            continue

        guesses = guesses + 1

        if guess < secret:
            print(f"Higher. {tries - guesses} left.")
        elif guess > secret:
            print(f"Lower. {tries - guesses} left.")
        else:
            won = True
            break

    if won:
        print(f"Correct. You took {guesses} of {tries} guesses.")
    else:
        print(f"Out of guesses. The number was {secret}.")

    again = input("Play again? (y/n): ").strip().lower()
    if again != "y":
        print("Thanks for playing.")
        break
PY

The round code is the same as before, moved four spaces to the right so it sits inside the new while True:. Two things are worth noticing:

  • There are now loops inside loops. break and continue only affect the nearest loop around them. The break after a correct guess ends the guessing loop, not the whole game, so the program goes on to Play again?. The break after again != "y" is in the outer loop, so it ends the game.
  • Every new round picks a new secret, because the random.randint line is inside the outer loop.
Bash
python3 game.py

Check it worked

Finish a round and answer y: the game asks for a level again and picks a new number. Finish a second round and answer n, or anything other than y: it prints Thanks for playing. and your prompt comes back.

Step 6 · Move the logic into functions and add a seed

The game works, but it is hard to test. The only way to check it is to play, and the secret number changes every time. Two changes fix that:

  • Move the decision "is this guess higher, lower or correct?" into its own function. A test can then call it with numbers it chooses, without any typing.
  • Let the player pass a seed on the command line. random.seed(7) sets the starting point of Python's random number generator, and from the same seed it produces the same numbers in the same order. A seeded game is the same game every time, which you can replay and check.

Replace game.py with this version. It plays exactly as before:

Bash
cat > game.py <<'PY'
import random
import sys

LEVELS = {
    "easy": {"top": 10, "tries": 5},
    "normal": {"top": 50, "tries": 7},
    "hard": {"top": 100, "tries": 7},
}


def check(guess, secret):
    """Return the hint for one guess: Higher, Lower or Correct."""
    if guess < secret:
        return "Higher"
    if guess > secret:
        return "Lower"
    return "Correct"


def ask_level():
    level = input("Level (easy, normal, hard): ").strip().lower()
    while level not in LEVELS:
        level = input("Type easy, normal or hard: ").strip().lower()
    return level


def ask_number(top):
    while True:
        text = input(f"Guess a number from 1 to {top}: ")
        try:
            number = int(text)
        except ValueError:
            print(f"{text!r} is not a whole number. Try again.")
            continue
        if 1 <= number <= top:
            return number
        print(f"Pick a number from 1 to {top}.")


def play_round():
    level = ask_level()
    top = LEVELS[level]["top"]
    tries = LEVELS[level]["tries"]
    secret = random.randint(1, top)
    guesses = 0

    while guesses < tries:
        guess = ask_number(top)
        guesses = guesses + 1
        hint = check(guess, secret)
        if hint == "Correct":
            print(f"Correct. You took {guesses} of {tries} guesses.")
            return
        print(f"{hint}. {tries - guesses} left.")

    print(f"Out of guesses. The number was {secret}.")


def main():
    if len(sys.argv) > 1:
        random.seed(int(sys.argv[1]))

    while True:
        play_round()
        again = input("Play again? (y/n): ").strip().lower()
        if again != "y":
            print("Thanks for playing.")
            break


if __name__ == "__main__":
    main()
PY

What each function does:

  • check(guess, secret) holds the comparison and returns a word instead of printing it. return hands the value back to whoever called the function and ends the function at once, which is why the second test can be a plain if rather than elif. The line in triple quotes is a docstring: a short description of the function.
  • ask_level() and ask_number(top) hold the two input loops. ask_number returns only once it has a valid number, so the code that calls it never sees bad input. 1 <= number <= top is Python's way of writing "number is between 1 and top", both included.
  • play_round() plays one round. Because ask_number filters bad input, the guess counter no longer needs continue, and return replaces the won variable.
  • main() reads the seed and runs the play-again loop. sys.argv is the list of words on the command line: sys.argv[0] is the script name, and sys.argv[1], if present, is the seed.
  • if __name__ == "__main__": runs main() only when you start the file with python3 game.py. When another file imports game, the functions are loaded but the game does not start. The next step depends on that.

Play with seed 7 on hard. Instead of typing, you can feed the answers in on standard input, one per line:

Bash
printf 'hard\n50\n25\n42\nn\n' | python3 game.py 7

printf writes the five answers, | passes them to the game as if you had typed them, and 7 is the seed. The prompts and replies run together on a few lines because no one pressed Enter on screen.

Check it worked

The output contains Lower. 6 left., then Higher. 5 left., then Correct. You took 3 of 7 guesses. and Thanks for playing. With seed 7, the first number on hard is always 42. Run the command again and you get the same output. Run python3 game.py 7 and type the answers yourself: same game. Run python3 game.py with no seed and the number is different each time, as before.

Step 7 · Write two tests

A test is code that checks other code and complains loudly when the answer is wrong. Python's assert statement does the job in one line: assert condition does nothing when the condition is true, and stops the program with an AssertionError when it is false.

Create test_game.py next to game.py:

Bash
cat > test_game.py <<'PY'
import random

from game import check

assert [check(30, 50), check(70, 50), check(50, 50)] == ["Higher", "Lower", "Correct"]

random.seed(7)
first_game = [random.randint(1, 100) for _ in range(3)]
random.seed(7)
assert [random.randint(1, 100) for _ in range(3)] == first_game

print("2 checks passed")
PY
python3 test_game.py

Line by line:

  • from game import check loads check from game.py. Thanks to the __name__ guard, importing does not start a game or wait for input.
  • The first assert calls check three times, with a guess below, above and equal to 50, and compares the list of answers with the list you expect.
  • The second test seeds the generator, draws three numbers, seeds it again with the same value and draws three more. The assert checks the two lists are equal, which is the promise that makes seeded replays work. [... for _ in range(3)] builds a list by repeating the expression three times; _ is the usual name for a loop variable you do not use.
  • print only runs if both asserts passed, because a failing assert stops the script before it gets there.

Now see a test fail. In game.py, change return "Higher" to return "higher" and run python3 test_game.py again. The script stops with a traceback ending in AssertionError and does not print 2 checks passed. Change it back to return "Higher" before you go on.

When you are finished with the project, you can delete the folder:

Bash
python3 test_game.py
cd ~
rm -rf ~/guessing-demo

The final python3 test_game.py above confirms game.py is back to the passing version before the folder goes.

Check it worked

python3 test_game.py prints 2 checks passed. With "higher" in lower case, it prints a traceback that points at the first assert line in test_game.py and ends in AssertionError. After the fix, it prints 2 checks passed again.

Next steps

You have a playable game, a way to replay any game exactly, and tests for the logic. Some ways to extend it, each a good exercise:

  • Keep a best score per level in a dictionary, such as best = {"easy": 3}, and print it at the end of each round.
  • Add a custom level that asks the player for the top number and works out the guess limit.
  • Save the best scores to a JSON file so they survive between runs, using what you learn in reading and writing files and JSON in Python.

To go deeper into the pieces you used:

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.