Python for Kids: Build a Number Guessing Game (Step by Step)
Write your first real Python program โ a number guessing game with hints, a guess counter, input checking and a "play again" option. Every line explained for beginners.
In this guide
- Step 1: Say hello
- Step 2: Pick a secret number
- Step 3: Ask for a guess
- Step 4: Give hints with if, elif and else
- Step 5: Keep guessing with a loop
- Step 6: Don't crash on bad input
- Step 7: The complete game
- How to win every time (the computer science secret)
- Common errors and what they mean
- Challenges to try next
- What you learned
- Frequently asked questions
"I'm thinking of a number between 1 and 100โฆ" โ the guessing game is the perfect first Python project. In about 25 lines of code you will use the most important ideas in programming: variables, input, conditions, loops and random numbers.
By the end, your game will:
- pick a secret number,
- tell the player "too high" or "too low" after each guess,
- count the guesses,
- cope with mistakes (like typing a word instead of a number),
- ask "Play again?".
What you need: Python 3. Download it free from python.org, or install Thonny (thonny.org), a beginner-friendly editor that comes with Python built in. On a Chromebook or school computer, you can use a free online Python editor such as Replit or Trinket.
Step 1: Say hello
Create a new file called guess.py and type:
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")Run it (in Thonny, click the green Run button or press F5). You will see the two messages.
print() shows text on the screen. Text inside quotes is called a string.
Step 2: Pick a secret number
Python can choose random numbers using its built-in random module.
import random
secret = random.randint(1, 100)
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")import randomloads Python's random-number tools.random.randint(1, 100)picks a whole number from 1 to 100 โ and both 1 and 100 can be chosen.secret = โฆstores that number in a variable calledsecret. A variable is a named box that holds a value.
Step 3: Ask for a guess
guess = int(input("Your guess: "))input()waits for the player to type something and press Enter. It always gives back text.int()turns that text into a whole number, so we can compare it withsecret.
Step 4: Give hints with if, elif and else
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print("You got it!")Python checks each condition in order:
ifโ is the guess smaller? Then say "Too low!"elif(short for else if) โ otherwise, is it bigger?elseโ if it is neither smaller nor bigger, it must be correct.
Indentation matters in Python. The four spaces before each print show that it belongs to the line above. Thonny and other editors add them for you after a colon (:).
Step 5: Keep guessing with a loop
Right now the player only gets one guess. A while loop repeats code while something is true.
import random
secret = random.randint(1, 100)
guess = 0
tries = 0
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
while guess != secret:
guess = int(input("Your guess: "))
tries = tries + 1
if guess < secret:
print("Too low! Try again.")
elif guess > secret:
print("Too high! Try again.")
else:
print(f"You got it in {tries} tries!")!=means "is not equal to". The loop keeps going until the guess matches.- We start
guessat0so the loop runs at least once (0 can never be the secret). tries = tries + 1adds one to the counter each time round.- The
fbefore the string makes it an f-string: anything inside{ }is replaced by its value, so the player sees "You got it in 6 tries!".
Run it and play a few rounds. ๐
Step 6: Don't crash on bad input
Try typing hello instead of a number. The program crashes with a ValueError, because int("hello") makes no sense. Real programs must cope with mistakes.
We can try the conversion and catch the error:
while True:
text = input("Your guess: ")
try:
guess = int(text)
break
except ValueError:
print("Please type a whole number.")while Trueloops forever โ until webreakout of it.- If
int(text)works,breakleaves the loop with a valid number. - If it fails, Python jumps to
except ValueErrorand asks again instead of crashing.
Step 7: The complete game
Here is the finished program with input checking, a range check, a guess counter and "play again":
import random
def get_guess():
"""Ask until the player types a whole number from 1 to 100."""
while True:
text = input("Your guess (1-100): ")
try:
number = int(text)
except ValueError:
print("That's not a whole number. Try again.")
continue
if 1 <= number <= 100:
return number
print("Please choose a number from 1 to 100.")
def play():
secret = random.randint(1, 100)
tries = 0
print("\nI'm thinking of a number between 1 and 100.")
while True:
guess = get_guess()
tries += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Correct! The number was {secret}. You took {tries} tries.")
return tries
print("Welcome to the Number Guessing Game!")
best = None
while True:
score = play()
if best is None or score < best:
best = score
print("That's your best score so far!")
again = input("Play again? (y/n): ").strip().lower()
if again != "y":
print(f"Thanks for playing! Your best was {best} tries.")
breakNew ideas in this version:
- Functions (
def get_guess():anddef play():) package code into named, reusable chunks.returnsends a value back to wherever the function was called. - The text in triple quotes under
def get_guess()is a docstring โ a note explaining what the function does. continuejumps straight back to the top of the loop.1 <= number <= 100checks that the number is in range โ Python lets you write it just like in maths.tries += 1is a shortcut fortries = tries + 1.best = Nonemeans "no best score yet". After each game we keep the smallest number of tries..strip().lower()removes spaces and makes the answer lowercase, soY,yandyall count as yes.\ninside a string starts a new line.
How to win every time (the computer science secret)
Is there a best strategy? Yes! Always guess the middle of the numbers that are still possible:
- Start with 50. "Too high" means the number is 1โ49, so guess 25.
- "Too low" means 26โ49, so guess 37, and so on.
Each guess cuts the possibilities in half, so you will always find the number in 7 guesses or fewer (because 2 ร 2 ร 2 ร 2 ร 2 ร 2 ร 2 = 128, which is more than 100). This strategy is called binary search, and computers use it to find things in huge lists incredibly fast.
Common errors and what they mean
| Error message | What it means | Fix |
|---|---|---|
IndentationError |
The spaces at the start of a line are wrong | Line code up exactly as shown; use 4 spaces |
NameError: name 'radom' is not defined |
A spelling mistake | Check spelling โ it's random |
SyntaxError near if or while |
A missing colon | Lines starting if, elif, else, while and def end with : |
ValueError: invalid literal for int() |
Text was turned into a number | Use the try/except version from Step 6 |
Challenges to try next
- Difficulty levels: ask "easy, medium or hard?" and pick a number up to 10, 100 or 1000.
- Limited guesses: the player loses after 10 wrong guesses.
- Hot or cold: if the guess is within 5 of the secret, print "๐ฅ Very hot!".
- Swap roles: you think of a number and the computer guesses it using binary search.
What you learned
- Variables, strings and numbers.
input()andint(), and why input must be checked.if,elifandelsefor decisions.whileloops,breakandcontinue.- Functions with
defandreturn. - Handling errors with
tryandexcept. - A real computer science idea: binary search.
If you have used Scratch before, you might notice these are the same ideas as Scratch's forever, if and variable blocks โ just written as text. Our guide to Scratch vs Python explains how the two connect.
Frequently asked questions
What age should children start learning Python? Many children are ready around 10 or 11, once they can type comfortably and read instructions carefully. Younger children often start with Scratch.
Is Python free? Yes. Python and editors such as Thonny and VS Code are completely free.
Why does my game pick the same number every time I test it? It doesn't โ random.randint picks a new number each run. If you set secret = 42 while testing, remember to change it back!
New to StemNest?
Book a free trial class and learn coding and AI live with our friendly tutors.
Book a free trial