Build a Python
number guessing game.
Give your code a little personality. Build a number guessing game that drops hints, handles mistakes, and celebrates a win.
- Beginner friendly
- Python 3
- No extra packages
Find the secret.
Tap a number. Follow the clues.
I’m thinking of a number from 1 to 20. What’s your first guess?
Type a whole number, or “quit” to leave. Invalid entries don’t count.
Browser preview of the game you’ll write in Python below.
Predict the rules before copying the code
One secret
The target stays the same until the round ends.
Useful hints
Every valid guess tells you which way to go.
Safe mistakes
Words and out-of-range numbers don’t use a turn.
You need a Python 3 editor with console input. If variables, input or indentation are new, start with our beginner Python learning path. Save this project as guessing_game.py, not random.py: using the library’s name for your file can stop Python importing the intended module.
Write down three rules: the secret number stays the same during a game; only a valid number between 1 and 20 increases the counter; and a correct guess or quit command ends the loop. These rules give you something specific to test rather than assuming that one successful run proves the game works.
Run the complete game
Here’s the complete game. Copy it into a Python 3 editor, save it as guessing_game.py, and run it. Then come back to unpack the decisions.
from random import randint
secret = randint(1, 20)
attempts = 0
while True:
entry = input("Guess 1 to 20, or type quit: ").strip()
if entry.lower() == "quit":
print("See you next time!")
break
try:
guess = int(entry)
except ValueError:
print("Please enter a whole number.")
continue
if not 1 <= guess <= 20:
print("Stay between 1 and 20.")
continue
attempts += 1
if guess < secret:
print("Too low.")
elif guess > secret:
print("Too high.")
else:
print(f"Correct in {attempts} valid guesses!")
break
Python 3 · Standard library only · No packages to install
Use your editor’s Run button, or run python guessing_game.py (on some systems, python3 guessing_game.py). The secret changes each round.
Understand where the program makes each decision
The secret is chosen before the loop. Choosing it inside the loop would move the target after every guess. randint(1, 20) can return either endpoint. The player’s entry is text: strip() removes surrounding spaces and the quit check happens before numeric conversion.
int(entry) raises ValueError when text cannot be read as an integer. The except block gives another chance without increasing attempts. The range check also runs before the counter changes. Consequently, “hello”, “3.5”, 0 and 21 are not valid guesses in this game.
After validation, the counter increases once. The comparison selects a low, high or correct response. continue starts the next loop iteration; break leaves the loop. A while loop is appropriate because the program cannot know the number of attempts in advance.
Test each branch with a known secret
Temporarily replace secret = randint(1, 20) with secret = 12. This makes the same test repeatable. Enter the sequence below in a single run; then restore the random line when you are finished.
| Input | Expected result | Valid-guess count |
|---|---|---|
| hello | Ask for a whole number. | 0 |
| 0 | Ask for a value between 1 and 20. | 0 |
| 5 | Too low. | 1 |
| 18 | Too high. | 2 |
| 12 | Correct; end the game. | 3 |
In a separate run, enter “ QUIT ” with spaces to check that leaving works before numeric conversion. Also test 1 and 20 to confirm that the endpoints are accepted. If an error message unexpectedly uses an attempt, check whether you incremented the counter too early.
Quick challenge: does “hello” use a guess?
No. The number conversion fails before the attempt counter changes. The player gets another chance. That’s input validation doing its job.
Extend one rule, then test it again
First add an attempt limit. Decide whether quitting should show the answer and whether invalid inputs should consume a turn; write the decision down before changing code. Next, let a player select a range, validating that the lower bound is smaller than the upper bound. Keep each version small enough to explain.
For the Python behaviour used here, consult the official randint reference and integer-conversion reference. The project code and test sequence on this page are original teaching examples. If you prefer guided projects, explore Knowledge Wave’s Programming Fundamentals course.
Common questions
How do I handle invalid input in a Python guessing game?
Read the entry as text and check for quit before converting it. Put int(entry) inside try/except ValueError, then reject numbers outside the game's range. Increase the attempt counter only after those checks pass. In this lesson, words, decimals and out-of-range numbers do not consume a valid guess.
Why does my Python guessing game keep changing the number?
The random-number call may be inside the guessing loop. Choose the secret once before the loop so that every guess is compared with the same target. Generate a new secret only when starting a new round. Temporarily use secret = 12 to make your tests repeatable.
Why use a while loop for a number guessing game?
The number of guesses is not known in advance. A while loop can keep asking until the player wins or enters quit. In the example, break ends the loop and continue starts the next turn after invalid input. A separate attempt limit would require an additional stopping rule.
Does randint include both the lowest and highest number?
Yes. Python's randint(1, 20) can choose either 1 or 20 as well as every integer between them. Use those same bounds in the prompt and input checks. This differs from range(1, 20), whose stopping value of 20 is excluded.
You didn’t just read it.
You made it work.
Try an attempt limit, invent a theme, or challenge a friend to play. Every small change is another reason to keep building.