Lesson 28 of 30 · Mini Projects
Project: Number Guessing Game
Build a complete number guessing game in Python, step by step. Practise variables, loops, conditions, functions, random numbers and error handling in one project.
- 8 min read
- Beginner
- Reviewed
- How to plan a program before writing it
- How to build a project in small steps that each work
- How to combine loops, conditions, functions, random numbers and error handling
- What a random seed is and why it matters in AI
What you will build
The computer picks a secret number between 1 and 20. The player has five attempts to guess it. After each guess, the program says too high or too low.
It is a small game, but it uses almost everything from this course. That is the point of a project: joining separate skills into one working program.
Plan first
Before writing code, describe the program in plain steps.
- Choose a secret number.
- Ask the player for a guess.
- Compare the guess with the secret and give a hint.
- Repeat until the guess is right or the attempts run out.
- Tell the player the result.
Professional programmers work the same way. We will build one step at a time and run the program after each.
Step 1: one guess
Start as simply as possible, with a fixed secret and a single guess.
secret = 7
guess = int(input("Guess the number (1-20): "))
if guess == secret:
print("Correct!")
else:
print("Wrong.")Step 2: give a hint
"Wrong" is not helpful. Use if, elif and else to say which way to go.
secret = 7
guess = int(input("Guess the number (1-20): "))
if guess == secret:
print("Correct!")
elif guess < secret:
print("Too low.")
else:
print("Too high.")Step 3: keep guessing
One guess is not a game. Limit the player to five attempts with a for loop, and break out as soon as the guess is correct.
secret = 7
for attempt in range(1, 6):
guess = int(input(f"Attempt {attempt} of 5: "))
if guess == secret:
print("Correct! Attempts used:", attempt)
break
elif guess < secret:
print("Too low.")
else:
print("Too high.")Step 4: a secret that changes
A game with a fixed answer is only fun once. The random module picks a different number each time.
import random
secret = random.randint(1, 20)
for attempt in range(1, 6):
guess = int(input(f"Attempt {attempt} of 5: "))
if guess == secret:
print("Correct! Attempts used:", attempt)
break
elif guess < secret:
print("Too low.")
else:
print("Too high.")
print("The number was", secret)Making randomness repeatable
Run that a few times and the secret keeps changing, which makes it hard to practise in the browser. Add one line, random.seed(42), straight after the import. A seed makes the "random" numbers come out the same on every run.
With a seed, you can run the program, read the hints, improve your guesses in the Input box and run it again until you win. Remove the seed for a real game.
Step 5: do not crash on bad input
If the player types ten, int() raises a ValueError and the game stops. Wrap the input in try and except, inside a loop that asks again.
def get_guess(attempt):
while True:
try:
return int(input(f"Attempt {attempt} of 5: "))
except ValueError:
print("Please type a whole number.")
guess = get_guess(1)
print("You guessed", guess)Putting this in a function keeps the main game short and readable.
The finished game
Here is everything together, organised into functions. Read it from the bottom: the last line starts the game.
import random
MAX_ATTEMPTS = 5
LOWEST = 1
HIGHEST = 20
def get_guess(attempt):
"""Ask until the player types a whole number."""
while True:
try:
return int(input(f"Attempt {attempt} of {MAX_ATTEMPTS}: "))
except ValueError:
print("Please type a whole number.")
def play():
"""Play one round of the guessing game."""
secret = random.randint(LOWEST, HIGHEST)
print(f"I am thinking of a number between {LOWEST} and {HIGHEST}.")
for attempt in range(1, MAX_ATTEMPTS + 1):
guess = get_guess(attempt)
if guess == secret:
print("Correct! Attempts used:", attempt)
return
if guess < secret:
print("Too low.")
else:
print("Too high.")
print("Out of attempts. The number was", secret)
play()Notice what changed from Step 4:
- The limits are constants at the top, written in capitals. To make the game harder, you change one line.
- Each function does one job and has a docstring.
returnleavesplay()as soon as the player wins, so nobreakis needed.
A winning strategy
With five attempts you can always win. Guess the middle of the remaining range each time: 10 first, then 5 or 15, and so on. Every guess halves the possibilities, and five halvings cover up to 32 numbers. This idea is called binary search, and it is one of the most famous algorithms in computing.
Make it your own
- Let the player choose a difficulty: 1 to 10, 1 to 50 or 1 to 100.
- Ask "Play again?" at the end and loop.
- Keep the best score and save it to a file.
- Reverse the game: you think of a number and the program guesses it using binary search.
Write the heart of the game as a reusable function. hint(guess, secret) must return the right message.
# Write a function called hint that takes a guess and a secret number. # It must RETURN one of: "Too low", "Too high" or "Correct!" # Do not change these lines. Output must be exactly: # Too high # Too low # Correct! print(hint(10, 7)) print(hint(3, 7)) print(hint(7, 7))
Why is random.seed(42) useful while you are testing a program?
Summary
- Plan a program in plain steps before coding.
- Build in small steps and run the program after each one.
- Put values that may change in constants at the top.
- Give each function one clear job.
- A seed makes random behaviour repeatable.
Next: a second project that works with the user's input.
Finished reading? Tick it off to track your progress.