๐ Python for kids ยท Class 6 ยท Lesson 17 of 18 ยท Free
Project: Number Guessing Game
โฑ About 40 minutes ยท โถ run real Python here โ nothing to install ยท no sign-in
In this lesson you will
- Combine input, if/elif/else and a while loop into one working game.
- Count attempts and limit tries with a for loop, break and else.
- Pick a secret number with the random module and wrap the game in a function.
I am thinking of a number between 1 and 100. Can you guess it in 7 tries? With good hints, you always can! Today you will build this game in Python, one step at a time, using everything you have learned.
How does a number guessing game work?
The computer keeps a secret number. The player guesses, and the computer says too high, too low or correct.
Big projects are easier in small steps. First we make one guess work. Then we add a loop, a counter and a limit.
To test properly, we start with a fixed secret number. That way the answer is the same every time we run it.
โถsecret = 422guess = int(input("Guess my number (1-100): "))3if guess < secret:4 print("Too low!")5elif guess > secret:6 print("Too high!")7else:8 print("Correct! You read my mind.")
No variables yet.
โโ๏ธ Change this code and run it yourself
Guess my number (1-100): 60 Too high!
How do I let the player keep guessing with a while loop?
One guess is not much of a game. A while loop repeats until the guess equals the secret.
We set guess to 0 before the loop. Otherwise Python would not know guess the first time it checks the condition.
When the player is correct, the condition becomes False and the loop stops by itself.
โถsecret = 422guess = 03while guess != secret:4 guess = int(input("Your guess: "))5 if guess < secret:6 print("Too low!")7 elif guess > secret:8 print("Too high!")9print("Correct! The number was", secret)
No variables yet.
โโ๏ธ Change this code and run it yourself
Your guess: 50 Too high! Your guess: 30 Too low! Your guess: 42 Correct! The number was 42
How do I count the number of tries?
Players love a score. We add a counter called tries that starts at 0 and goes up by 1 for each guess.
Then we can praise fast players differently. An if after the loop checks the score.
This is a good use of the counter pattern you have seen with loops before.
Your guess: 50 Too high! Your guess: 25 Too low! Your guess: 37 Too low! Your guess: 43 Too high! Your guess: 42 Got it in 5 tries!
How do I give the player only 5 tries?
A limit makes the game exciting. A for loop with range(5) gives exactly 5 rounds.
If the guess is correct, break ends the loop early. If all 5 tries are used up, the for-else part runs.
This is the search pattern from the loop patterns lesson, used in a game.
Try 1 of 5: 50 Too high! Try 2 of 5: 40 Too low! Try 3 of 5: 45 Too high! Try 4 of 5: 41 Too low! Try 5 of 5: 44 Too high! Out of tries! The number was 42
How do I make the computer pick a random number?
A real game needs a new secret each time. Python's random module can pick one for us.
First write import random at the top. Then random.randint(1, 100) gives a whole number from 1 to 100, both included.
We also wrap the game in a function, so play_game() can start a new round anytime.
I picked a number from 1 to 3. Your guess: 2 Lucky! Right first time.
๐ก The output changes every run, because the secret is random. Run it a few times to see.
What is the smartest way to guess?
Always guess the middle of the numbers that are still possible. Each hint then cuts the choices in half.
From 1 to 100, halving gives 50, 25, 13, 7, 4, 2, 1 choices. So 7 tries are always enough.
Computers use this idea, called binary search, to find things fast. Here the computer plays against itself.
Computer guesses 50 Computer guesses 75 Computer guesses 62 Computer guesses 68 Computer guesses 71 Computer guesses 73 Found 73 in 6 tries.
๐ค Predict the output
Think like Python: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
secret = 7
for guess in [3, 9, 7]:
if guess < secret:
print("low")
elif guess > secret:
print("high")
else:
print("win")Question 2. What does this print?
secret = 5
tries = 0
for guess in [1, 5, 8]:
tries = tries + 1
if guess == secret:
break
print(tries)Question 3. What does this print?
low = 1 high = 20 guess = (low + high) // 2 print(guess)
๐งฉ Your challenge
Make a "hot or cold" version. The secret is 30. Give the player 4 tries. If a guess is within 5 of the secret (but not equal), print "Hot!". Otherwise print "Cold!". Print "You win!" on a correct guess, or reveal the number after 4 wrong tries.
Try 1: 10 Cold! Try 2: 27 Hot! Try 3: 33 Hot! Try 4: 30 You win!
โ ๏ธ Common mistakes (and how to fix them)
โ Wrong
secret = 42
guess = input("Guess: ")
if guess < secret:
print("Too low!")TypeError: '<' not supported between instances of 'str' and 'int'
โ Right
secret = 42
guess = int(input("Guess: "))
if guess < secret:
print("Too low!")input() always gives text. Python cannot compare text with a number, so convert it with int().
โ Wrong
secret = 42
while guess != secret:
guess = int(input("Guess: "))
print("Correct!")NameError: name 'guess' is not defined
โ Right
secret = 42
guess = 0
while guess != secret:
guess = int(input("Guess: "))
print("Correct!")The while line checks guess before anyone has typed. Give guess a starting value, like 0, above the loop.
โ Wrong
secret = 42
guess = 0
while guess != secret:
guess = int(input("Guess: "))
tries = 0
tries = tries + 1
print("Tries:", tries)No error message โ but it always says Tries: 1.
โ Right
secret = 42
guess = 0
tries = 0
while guess != secret:
guess = int(input("Guess: "))
tries = tries + 1
print("Tries:", tries)tries = 0 inside the loop resets the counter every round. Set starting values once, before the loop.
๐ Remember
- Build a game in small steps: one guess, then a loop, then a counter, then a limit.
- Test with a fixed secret so the results are the same every run.
- while guess != secret repeats until the player is right.
- for turn in range(1, 6) with break and else gives exactly 5 tries.
- import random and random.randint(a, b) pick a random whole number from a to b.
- Guessing the middle each time (binary search) finds 1โ100 in at most 7 tries.
Finished the quiz and the challenge?
Questions students ask
Does random.randint include both end numbers?
Yes. random.randint(1, 100) can give 1, 100 or anything between them.
Why do I get a TypeError comparing my guess?
input() returns text, not a number. Wrap it in int() before comparing with the secret.
How can I let the player play again?
Put the game in a function, then call it inside a while True loop. Break when the player types no.
Why test with a fixed secret number first?
A fixed secret gives the same result every run. That makes bugs easy to find before you add random.