Python Number Guessing Game Example
A number guessing game is a great beginner project because it combines several core Python ideas in one small program.
In this example, Python picks a random number, asks the user to guess it, and keeps running until the correct answer is entered. The goal here is not just to copy the code, but to understand how each part works.
Quick example
This is the shortest working version:
import random
secret_number = random.randint(1, 10)
while True:
guess = int(input("Guess a number from 1 to 10: "))
if guess == secret_number:
print("You guessed it!")
break
elif guess < secret_number:
print("Too low")
else:
print("Too high")
This version uses:
random.randint()to choose a secret numberinput()to get the user's guessint()to turn text into a number- a
whileloop to keep asking if,elif, andelseto check the guessbreakto stop the loop when the user wins
What this example teaches
This project helps you practice how to:
- combine input, loops, and conditions in one small project
- generate a random number with
random.randint() - compare a user guess with a secret number
- stop a loop when the correct answer is found
How the game works
The program follows a simple pattern:
- The program picks a random number.
- The user enters a guess.
- The program checks whether the guess is too low, too high, or correct.
- The loop repeats until the user guesses correctly.
That makes this a good first project because each step is easy to follow.
Code walkthrough
Here is the same program again:
import random
secret_number = random.randint(1, 10)
while True:
guess = int(input("Guess a number from 1 to 10: "))
if guess == secret_number:
print("You guessed it!")
break
elif guess < secret_number:
print("Too low")
else:
print("Too high")
Import the random module
import random
Python needs the random module before it can use random number tools.
If you forget this line, the program will fail when it reaches random.randint(). For a broader overview, see the Python random module overview.
Store the secret number in a variable
secret_number = random.randint(1, 10)
This line creates a random integer from 1 to 10 and stores it in secret_number.
random.randint(1, 10)includes both 1 and 10- the value stays the same for the whole game
- the user does not see this number
Use input() to get a guess
guess = int(input("Guess a number from 1 to 10: "))
This does two things:
input(...)shows a message and waits for the user to type somethingint(...)converts that text into a whole number
This matters because input() always returns text. If you want more help with this step, see how to convert user input to numbers in Python.
Use a while loop to keep asking
while True:
This creates a loop that runs again and again.
Because True is always true, the loop keeps going until something stops it. In this program, break stops it when the guess is correct.
Use if, elif, and else to compare the guess
if guess == secret_number:
print("You guessed it!")
break
elif guess < secret_number:
print("Too low")
else:
print("Too high")
This comparison block checks three cases:
- if the guess matches the secret number, the player wins
- if the guess is smaller, the program says
"Too low" - otherwise, the guess must be bigger, so it says
"Too high"
If you want a full beginner explanation of this pattern, see Python if, else, and elif explained.
Use break to end the loop
break
Without break, the loop would continue forever, even after the correct guess.
That is why break must be inside the correct if block.
Beginner version to show first
When you build your first guessing game, keep it simple:
- use a small range such as 1 to 10
- use one loop and one comparison block
- avoid advanced features like functions at first
- test the program after every small change
Here is a beginner-friendly version again:
import random
secret_number = random.randint(1, 10)
while True:
guess = int(input("Guess a number from 1 to 10: "))
if guess == secret_number:
print("You guessed it!")
break
elif guess < secret_number:
print("Too low")
else:
print("Too high")
Example run:
Guess a number from 1 to 10: 4
Too low
Guess a number from 1 to 10: 8
Too high
Guess a number from 1 to 10: 6
You guessed it!
Useful improvements
Once the basic game works, you can improve it in small steps.
Count the number of guesses
This version tracks how many times the user guessed:
import random
secret_number = random.randint(1, 10)
guess_count = 0
while True:
guess = int(input("Guess a number from 1 to 10: "))
guess_count += 1
if guess == secret_number:
print("You guessed it!")
print("Guesses:", guess_count)
break
elif guess < secret_number:
print("Too low")
else:
print("Too high")
Validate input to avoid crashes
If the user types letters, int() raises a ValueError. This safer version checks the input first:
import random
secret_number = random.randint(1, 10)
while True:
user_text = input("Guess a number from 1 to 10: ")
if not user_text.isdigit():
print("Please enter a whole number.")
continue
guess = int(user_text)
if guess == secret_number:
print("You guessed it!")
break
elif guess < secret_number:
print("Too low")
else:
print("Too high")
Limit the number of attempts
You can also stop the game after a fixed number of guesses:
import random
secret_number = random.randint(1, 10)
attempts_left = 3
while attempts_left > 0:
guess = int(input("Guess a number from 1 to 10: "))
if guess == secret_number:
print("You guessed it!")
break
elif guess < secret_number:
print("Too low")
else:
print("Too high")
attempts_left -= 1
print("Attempts left:", attempts_left)
if attempts_left == 0 and guess != secret_number:
print("Game over. The number was", secret_number)
Let the user play again
A good next step is wrapping the game in another loop so the user can start a new round after winning.
Common problems in this project
Here are the most common beginner mistakes in a guessing game.
ValueError when converting input
Problem:
- you type letters like
hello - the program uses
int()on that text - Python crashes with
ValueError
Example:
guess = int(input("Guess a number: "))
If the user enters hello, this line fails.
Fixes:
- only enter number text such as
5 - validate the input before calling
int() - read ValueError: invalid literal for int() with base 10
Infinite loop because break is missing
If break is missing, the loop never ends after the correct answer.
Wrong idea:
if guess == secret_number:
print("You guessed it!")
Better:
if guess == secret_number:
print("You guessed it!")
break
Wrong indentation
Indentation controls which lines belong inside the loop or inside an if block.
For example, this is wrong:
while True:
guess = int(input("Guess a number: "))
Python expects the loop body to be indented.
Correct version:
while True:
guess = int(input("Guess a number: "))
If you see this kind of problem, read IndentationError: expected an indented block.
Forgetting to import random
If you use random.randint() without import random, Python does not know what random means.
Always include:
import random
Other common causes
These mistakes also happen often:
- using
input()without converting the result toint()before comparing with a number - typing words like
hellowhen the program expects a number - placing
breakoutside the correctifblock - misspelling
randintorrandom - using incorrect indentation in the loop
FAQ
Why does input() need int() here?
input() returns text. int() changes that text into a number so it can be compared with the secret number.
Why use a while loop in a guessing game?
A while loop lets the program keep asking until the correct guess is entered.
Why does my program crash when I enter letters?
int() can only convert valid number text. If the user types letters, Python raises a ValueError.
Can I make the game harder?
Yes. Increase the number range, limit attempts, or add hints.
See also
- Python random module overview
- random.randint() function explained
- Python input() function explained
- Python int() function explained
- Python while loops explained
- How to convert user input to numbers in Python
Build the basic game first and make sure you understand every line. After that, improve it by adding input validation and a guess counter.