Module 06 · Lesson 01
Project: Number Guessing Game
Build a number guessing game step by step: pick a secret with random, loop until the player wins or runs out of attempts, give higher or lower hints, and check the input.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Pick a random secret
- Hint with if and elif
- Loop through guesses
- Test with a function
The game in four parts
The computer picks a secret number. The player guesses, and gets a hint after every wrong guess.
Pick a secret
random.randint(1, 20)picks a whole number from 1 to 20, both ends included.Loop
Keep taking guesses until the player is right or runs out of tries.
Hint
if,elifandelsesay too high, too low or correct.Check
A guess that is not a number gets a friendly message, not a crash.
The same idea, elsewhere
Guess, get a hint, guess again: it powers more than games.
- Higher or lowerCard and quiz games where each answer narrows the next guess.
- Daily word puzzlesEach guess colours letters as hints for the next try.
- Searching fastComputers find a name in a sorted list of millions by guessing the middle and halving.
- Escape roomsLock codes with clue lights are a guessing loop in hardware.
Picking the secret
One line chooses the number the player must find. Tap each part to see its job.
Part 1 of 5
name:Stores the number so every later guess is checked against the same one.
Build the game in five steps
Build the project one step at a time. Each example runs on its own: change it, then press Run.
Example 1 of 61. Secret
Run this a few times. The secret changes each run.
Your turn: Make the range 1 to 100. Then pick a dice roll from 1 to 6.
import random
secret = random.randint(1, 20)
print("I picked", secret)Press Run to see what it prints.Watch a game play itself
Press Step to run one line at a time. The list stands in for three guesses a player typed.
Ready. Press Step to run the first line.
- secret = 7
- guesses = [10, 4, 7]
- for guess in guesses:
- if guess < secret:
- print(guess, "is too low")
- elif guess > secret:
- print(guess, "is too high")
- else:
- print(guess, "is right!")
- break
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.The secret is from 1 to 100. Which first guess is smartest?
0 of 6 answered
Common game misconceptions
Each card is something beginners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
import random
random.seed(7) # repeatable while testing
secret = random.randint(1, 20) # 1 to 20, both included
while attempts < MAX_ATTEMPTS:
...
if guess == secret:
break
text.isdigit() # check before int(text)Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
The game with a list of guesses
Run the full game logic with a fixed secret and a list of guesses instead of input(), so the output is the same every time.
def hint(guess, secret):
if guess == secret:
return "correct"
if guess < secret:
return "higher"
return "lower"
secret = 13
guesses = [10, 15, 12, 13, 18]
attempts = 0
for guess in guesses:
attempts += 1
result = hint(guess, secret)
print(f"{guess}: {result}")
if result == "correct":
print(f"Won in {attempts} attempts")
break
else:
print(f"Out of guesses. It was {secret}.")Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Comparing the guess as text
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
secret = 7
guess = input("Guess: ")
if guess == secret:
print("Correct!")Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Everyday life
Finding a page in a book
Looking up page 137 in a 300 page book, most people open near the middle and adjust. The halving strategy from the game finds any page in very few steps.
Why Python fits
Each step looks at the middle of the pages still possible and discards half of them. Even a 300 page book needs at most 9 steps this way, the same reason a 1 to 100 guessing game never needs more than 7 guesses.
Pythontarget = 137 low, high = 1, 300 steps = 0 while True: steps += 1 middle = (low + high) // 2 if middle == target: break if middle < target: low = middle + 1 else: high = middle - 1 print(f"Found page {target} in {steps} steps")OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Why do the Labs use a list of guesses?
How do I add a play-again option?
Is the computer's number really random?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.