Skip to content
Tutorials Center
My learning

Topics

Lesson 132 of 149 ยท Projects

Project: Number Guessing Game

Build a complete number guessing game in Python, step by step. Practice random numbers, loops, input validation, functions, difficulty levels and replay stats.

Time to build something. In this project you'll write a classic game: the computer picks a secret number, and the player guesses until they find it, with "higher" and "lower" hints along the way. It's small enough to finish in one sitting, yet it uses a surprising amount of what you've learned: random numbers, while loops, input, type conversion, exceptions, functions and dictionaries.

You'll build the game in six stages. Each stage is a complete, runnable program that adds one feature to the previous one, so you can run it, see what changed, and experiment before moving on.

How the editor plays the game

A game needs a player typing guesses. In these editors, input() reads its answers from the Input box under the code, one line per call. Each stage comes with guesses already filled in, so pressing Run plays a full game. Change the lines in the Input box to play differently. If the program asks for more input than the box contains, you'll get an EOFError; just add more lines.

There's one more trick. A random secret would make the preset guesses useless, so every stage calls random.seed(2024) first. Seeding makes the "random" numbers repeatable: with the same seed, randint() returns the same sequence every time. Delete the seed line when you want a truly random game (and then play by editing the Input box).

Stage 1: a secret and one guess

Start with the core: pick a number, ask for one guess, and compare.

Python Stage 1: one guess

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

random.randint(a, b) returns a whole number from a to b, including both ends. input() always returns a string, so int() converts it before the comparison; comparing the string "50" with the number 61 would raise a TypeError.

Stage 2: keep guessing

One guess isn't much of a game. A while loop keeps asking until the guess is right. Because we don't know in advance how many rounds it takes, while fits better than for:

Python Stage 2: loop until correct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

while True loops forever, and break jumps out the moment the player wins. The preset guesses follow the smartest strategy, halving the range each time: 50, then 75, then 62 and so on. With that strategy, any number from 1 to 100 takes at most seven guesses, because 2 to the 7th power (128) is more than 100. Keep that number in mind for stage 4.

Stage 3: handle bad input

Type fifty into stage 2 and the program crashes with a ValueError. Real users mistype all the time, so the game should complain politely and ask again. Let's move the asking into its own function that only returns once it has a valid number in range:

Python Stage 3: validate every guess

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The pattern inside ask_for_guess() is worth memorizing: loop, try to convert, continue on failure, return on success. It works for any program that needs valid input. Notice the chained comparison low <= guess <= high, which reads just like math. Also, .strip() removes stray spaces so " 75 " still counts.

Stage 4: count attempts and set a limit

A game where you can't lose isn't very exciting. Let's count attempts and allow at most seven. A for loop over range(1, max_attempts + 1) counts for us, and the loop's else clause runs only if the loop finished without a break, which is exactly the "ran out of guesses" case:

Python Stage 4: limited attempts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The preset guesses this time count up by tens, a poor strategy, so you'll see the losing message. Replace them with 50 75 62 56 59 61 (one per line) to win. The conditional expressions such as 'try' if attempt == 1 else 'tries' keep the messages grammatical: "1 try left", "2 tries left".

Stage 5: difficulty levels and a play_round() function

The main game logic is now big enough to deserve a function. Wrapping one round in play_round() also makes it easy to replay later. While we're at it, let's add difficulty levels. A dictionary maps each level name to its settings, so adding a new level is a one-line change:

Python Stage 5: difficulty levels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

play_round() returns a result instead of only printing it: the number of attempts on a win, or None on a loss. That return value is what will let the next stage keep score. The type hint int | None documents both possibilities (see Type Hints).

The loss case no longer needs the loop's else: if the player wins, return leaves the function, so any code after the loop runs only when every attempt was used.

Stage 6: play again and keep score

The finished game lets the player play as many rounds as they like and prints statistics at the end. A main() function ties everything together, and a small ask_yes_no() helper handles the "play again?" question:

Python Stage 6: the complete game

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

That's a complete program. A few design choices are worth pointing out:

  • Each function does one job. ask_for_guess() knows nothing about secrets, and play_round() knows nothing about statistics. You could swap the text interface for a graphical one by rewriting only the input functions.
  • Settings live in one place. LEVELS is a constant at the top, written in UPPER_SNAKE_CASE as PEP 8 suggests.
  • Data flows through return values. play_round() returns a result, main() collects results in a list, and print_stats() turns the list into a report. No global variables are needed.
  • [attempts for attempts in results if attempts is not None] is a list comprehension that keeps only the wins.

Running it on your computer: save the code as guess.py, delete the random.seed(2024) line, and replace the final main() call with the usual guard, if __name__ == "__main__": main(), so the game only starts when the file is run directly (see Modules and Imports). Then run python guess.py in a terminal.

Ideas to extend the game

Try these on your own, starting from stage 6:

  1. Warmer and colder. Instead of just "too low", say "very close!" when the guess is within 3 of the secret.
  2. Remember past guesses. Keep a set of guesses and warn when the player repeats one.
  3. Reverse roles. Write a mode where you think of a number and the computer guesses it by halving the range, while you answer higher, lower or correct.
  4. A points system. Award more points for fewer attempts and for harder levels, and show a running total.
  5. Tests. Move the input functions aside and write unit tests for a pure function such as make_hint(guess, secret).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which values can random.randint(1, 100) return?

    Unlike range(), randint includes both of its arguments.
  2. 2. Why does every stage call random.seed(2024)?

    Seeding fixes the sequence of random numbers, so the same secret comes up every run. Remove it for a truly unpredictable game.
  3. 3. In stage 4, when does the else block after the for loop run?

    A loop's else clause runs only if the loop ended normally, which here means every attempt was used without a correct guess.
  4. 4. Why does play_round() return the number of attempts instead of only printing it?

    Returning values lets the caller collect results and build features like stats on top, without global variables.

Summary

  • random.randint(a, b) picks a whole number including both ends; random.seed() makes the sequence repeatable for testing.
  • A while True loop with break repeats until a goal is reached; a for loop with range() caps the number of attempts, and its else handles "ran out".
  • The loop, try, continue, return pattern turns unreliable user input into valid values.
  • Splitting the game into small functions with return values made levels, replays and statistics easy to add.
  • A dictionary of settings keeps configuration in one place.

Next: Project: Tic-Tac-Toe.