Build a Number Guessing Game in Python
Code a complete number guessing game in Python: the computer picks a secret number, you guess, and it gives higher/lower hints. Learn loops, input, conditionals and replay — with full runnable code and a quiz.
Key takeaways
- random.randint(1, 100) picks the secret number the player must guess
- A while loop keeps asking until the guess is correct, then breaks
- int(input(...)) turns the typed answer into a number you can compare
- if/elif/else gives 'too high' or 'too low' hints to guide the player
- Counting guesses and offering a replay turns a script into a real game
A classic first game
The number guessing game is the "hello world" of game programming. The computer thinks of a secret number, you try to guess it, and after each guess it tells you whether to go higher or lower. It is short enough to finish in one sitting but uses real programming ideas you'll reuse forever: loops, input, comparisons and conditions.
If you've already written your first Python program, you have everything you need. Let's build it piece by piece, then put it all together.
Step 1: pick a secret number
The computer needs to choose a number the player can't predict. That is exactly what the random module is for:
import random
secret = random.randint(1, 100)
random.randint(1, 100) returns a whole number from 1 to 100, with both ends included. Because it's random, every game is different. (For a deeper look at randomness, see random numbers and games in Python.)
Step 2: ask the player to guess
We use input() to read what the player types. But input() always gives back text, and you can't compare text with a number, so we wrap it in int():
guess = int(input("Guess a number from 1 to 100: "))
If the player types 42, then guess becomes the number 42, ready to compare.
Step 3: give a hint
Now compare the guess with the secret and react:
if guess < secret:
print("Too low! Try higher.")
elif guess > secret:
print("Too high! Try lower.")
else:
print("Correct!")
The if/elif/else handles all three cases: below, above, or spot on. (Need a refresher? See making decisions with if.)
Step 4: keep asking with a loop
One guess isn't a game. We want to keep asking until the player wins, so we wrap the asking and hinting in a while True: loop and break out when correct:
while True:
guess = int(input("Your guess: "))
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print("You got it!")
break
while True: means "loop forever" — until something stops it. The break is that stop: it fires only when guess == secret.
The complete game
Here is the whole thing, with a guess counter and a replay option so it feels finished:
import random
def play_round():
secret = random.randint(1, 100)
guesses = 0
print("I'm thinking of a number between 1 and 100.")
while True:
guess = int(input("Your guess: "))
guesses += 1
if guess < secret:
print("Too low! Try higher.")
elif guess > secret:
print("Too high! Try lower.")
else:
print(f"Correct! The number was {secret}.")
print(f"You found it in {guesses} guesses.")
break
# Main game loop with replay
print("=== NUMBER GUESSING GAME ===")
while True:
play_round()
again = input("Play again? (yes/no): ").lower()
if again != "yes":
print("Thanks for playing!")
break
What each part does:
play_round()runs one complete game: pick a secret, loop until guessed, count tries.guesses += 1is short forguesses = guesses + 1. It counts every attempt.- The outer
while True:lets the player start a fresh round..lower()makes the answer lowercase soYES,Yesandyesall work. - If they type anything other than
yes, webreakand say goodbye.
A sample run looks like:
I'm thinking of a number between 1 and 100.
Your guess: 50
Too high! Try lower.
Your guess: 25
Too low! Try higher.
Your guess: 37
Correct! The number was 37.
You found it in 3 guesses.
Play again? (yes/no): no
Thanks for playing!
The winning strategy
Always guess the middle of the remaining range. Start at 50. If it's "too high", the answer is 1–49, so guess 25. If "too low", guess 75. Each guess cuts the possibilities in half, so you can win in 7 guesses or fewer every time. This trick is called binary search, and it's one of the most important ideas in computing.
Try it yourself
Upgrade your game with these challenges:
- Add difficulty levels. Ask the player to pick easy (1–20), medium (1–100) or hard (1–1000) and set the range with an
if/elif/elsebefore picking the secret. - Limit the guesses. Give the player only 7 tries. Count them, and if they run out, reveal the number and print "Game over!" Use a while loop condition like
while guesses < 7:. - Track a high score. Remember the fewest guesses across rounds and print it at the end.
- Reverse it. Make you think of a number and let the computer guess, always picking the middle of its range. Watch binary search in action!
Quick quiz
Test yourself and earn XP
Which line makes the computer pick a secret number from 1 to 100?
random.randint(1, 100) returns a whole number between 1 and 100, both ends included.
Why do we wrap input in int(), like int(input('Guess: '))?
input always returns a string. int() converts '42' into the number 42 so it can be compared with the secret.
What does break do in the guessing loop?
break exits the while loop immediately, ending the round once the correct number is found.
How do we count how many tries the player used?
We start guesses at 0 and add 1 inside the loop on every attempt.
What is the fastest guessing strategy for 1–100?
Guessing the middle and halving the range (binary search) always wins in 7 tries or fewer.
FAQ
int('hello') crashes the program with a ValueError. To handle that politely, wrap the input in a try/except block and ask again if the conversion fails. Until you learn error handling, just remind players to type digits only.
Change the range or limit the guesses. random.randint(1, 1000) is harder; random.randint(1, 20) is easier. You can also count guesses and end the game with a 'You lost!' message once the player passes a maximum number of tries.
Keep exploring
More in Coding