The number guessing game is usually the very first Python game people write: the computer thinks of a number and answers "too high" or "too low" until you find it. It uses just three ideas (a random number, a loop and an if), yet it is fun to play.
This version adds difficulty levels, counts your guesses and tells you if your answer isn't a number. Try to win in as few guesses as you can.
Play Number Guessing Game
Press โถ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (33 lines)
How to play
- Choose easy (1-10), normal (1-50) or hard (1-100).
- Type a guess. The game says whether the secret number is higher or lower.
- Find it to win. Try halving the range each time!
The complete Number Guessing Game code
Here is the whole program (33 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.
import random
LEVELS = {"easy": 10, "normal": 50, "hard": 100}
print("NUMBER GUESSING GAME")
level = input("Pick a level - easy, normal or hard: ").strip().lower()
if level not in LEVELS:
print("I'll use normal.")
level = "normal"
top = LEVELS[level]
secret = random.randint(1, top)
guesses = 0
print(f"I'm thinking of a number from 1 to {top}.")
while True:
text = input("Your guess: ").strip()
if not text.isdigit():
print("That's not a whole number. Try again.")
continue
guess = int(text)
guesses += 1
if guess < secret:
print("Higher!")
elif guess > secret:
print("Lower!")
else:
print(f"Correct! The number was {secret}.")
break
if guesses == 1:
print("First try. Amazing!")
else:
print(f"You found it in {guesses} guesses.")How the Number Guessing Game game works, step by step
01Choose a secret number
random.randint(1, top) returns a whole number between 1 and top, including both ends. The difficulty dictionary decides what top is.
LEVELS = {"easy": 10, "normal": 50, "hard": 100}
secret = random.randint(1, LEVELS[level])02Loop until the guess is right
while True repeats forever, and break leaves the loop the moment the guess matches. This pattern is perfect when you don't know how many tries it will take.
while True:
...
else:
break03Turn text into a number safely
input() returns text. Calling int("seven") would crash, so we check .isdigit() first and use continue to ask again.
if not text.isdigit():
print("That's not a whole number.")
continue
guess = int(text)04Give a hint
An if / elif / else chain compares the guess with the secret: lower, higher or equal. A counter goes up by one each valid guess.
if guess < secret:
print("Higher!")
elif guess > secret:
print("Lower!")What you'll learn
random.randint()while Truewithbreakandcontinue- Comparisons and
if / elif / else - Converting input with
int() - Counting with a variable
Python concepts in this game:
Number Guessing Game coding challenges
Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).
The hint function
Write hint(guess, secret) that returns "Higher!", "Lower!" or "Correct!".
Hint
If the guess is smaller than the secret, the player must go higher.
Show a solution
def hint(guess, secret):
if guess < secret:
return "Higher!"
if guess > secret:
return "Lower!"
return "Correct!"
print(hint(3, 7))Count the guesses
The secret is 6. Read guesses with input() until one equals 6, then print exactly Got it in 3 guesses (with the real count).
Hint
while guess != secret: then read a guess with int(input(...)) and add 1 to count.
Show a solution
secret = 6
count = 0
guess = 0
while guess != secret:
guess = int(input("Guess: "))
count += 1
print("Got it in", count, "guesses")Best possible score
With smart halving you can always find a number from 1 to top in a fixed number of guesses. Write max_guesses(top) that returns how many: keep halving top (with //) until it reaches 0, counting the steps. max_guesses(100) is 7.
Hint
while top > 0: then top = top // 2 and steps += 1.
Show a solution
def max_guesses(top):
steps = 0
while top > 0:
top = top // 2
steps += 1
return steps
print(max_guesses(100))Make it your own
Once your challenges pass, try one of these upgrades:
- Limit the player to a set number of guesses per level.
- Reverse it: you think of a number and the computer guesses.
- Keep a best score for each level.
- Say "very close!" when the guess is within 3.
Frequently asked questions
How do you make a number guessing game in Python?
Use random.randint() to choose a secret number, then a while loop that reads guesses with input(), converts them with int(), and prints Higher or Lower until the guess is correct.
Why does my guessing game crash when I type a word?
int() can only convert digits. Check the text with .isdigit() first, or wrap int() in try/except ValueError, and ask again.
What is the fastest way to win?
Always guess the middle of the numbers that are left. That halves the range each time, so 1-100 never takes more than 7 guesses.