Guess the Number Game
Abstract
“Guess the Number” is the rite-of-passage game in every beginner curriculum, and for good reason: in a single short script you exercise nearly every fundamental — randomness, looping, branching, user input, type conversion, comparisons, and string formatting. The premise: the computer secretly chooses a number between 1 and 20, the user has six chances to guess it, and after every guess the program tells them whether they were too high or too low.
In this tutorial we will:
- Build the classic version from scratch.
- Walk line-by-line through what each statement does.
- Harden the program against bad input (letters, negative numbers, empty input).
- Extend it with difficulty levels, score tracking, and a “play again” loop.
Prerequisites
- Python 3.6 or above.
- A text editor or IDE.
- Familiarity with running a Python script (see Hello World).
- Some comfort with
input()input(),print()print(), and basic comparisons.
Concepts You Will Use
random.randint(a, b)random.randint(a, b)— picks a random integer betweenaaandbb, inclusive.forforloop withrangerange— iterates a fixed number of times.ifif/elifelif/elseelse— choose between several branches.breakbreak— exit a loop immediately.- Type conversion —
int(input(...))int(input(...))turns text into a number. - String concatenation vs. f-strings — two ways to insert values into messages.
Getting Started
Create the project
- Make a folder named
guess-the-numberguess-the-number. - Inside it, create a file named
guessthenumber.pyguessthenumber.py. - Open the folder in your editor.
Write the code
Paste the following into guessthenumber.pyguessthenumber.py:
Guess The Number
Source# Guess the number game
import random
print('Hello, what is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess. You have ' + str(7 - guessesTaken) + ' guesses left.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber) + '.')# Guess the number game
import random
print('Hello, what is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess. You have ' + str(7 - guessesTaken) + ' guesses left.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber) + '.')Save, open a terminal in the folder, and run:
C:\Users\username\Documents\guess-the-number> python guessthenumber.py
Hello, what is your name?
Ravi
Well, Ravi, I am thinking of a number between 1 and 20.
Take a guess. You have 6 guesses left.
23
Your guess is too high.
Take a guess. You have 5 guesses left.
12
Your guess is too high.
Take a guess. You have 4 guesses left.
11
Your guess is too high.
Take a guess. You have 3 guesses left.
7
Your guess is too high.
Take a guess. You have 2 guesses left.
5
Good job, Ravi! You guessed my number in 5 guesses.C:\Users\username\Documents\guess-the-number> python guessthenumber.py
Hello, what is your name?
Ravi
Well, Ravi, I am thinking of a number between 1 and 20.
Take a guess. You have 6 guesses left.
23
Your guess is too high.
Take a guess. You have 5 guesses left.
12
Your guess is too high.
Take a guess. You have 4 guesses left.
11
Your guess is too high.
Take a guess. You have 3 guesses left.
7
Your guess is too high.
Take a guess. You have 2 guesses left.
5
Good job, Ravi! You guessed my number in 5 guesses.Run it a few times. The secret number changes every time.
Step-by-Step Explanation
1. Import randomness
import randomimport randomThe randomrandom module is part of Python’s standard library. After this line, random.randint(...)random.randint(...) is available.
2. Greet the user
print('Hello, what is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 and 20.')print('Hello, what is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 and 20.')input()input()waits for the user to press Enter and returns their text as a string.'Well, ' + name + ', ...''Well, ' + name + ', ...'is string concatenation — joining pieces of text with++.
💡 A more modern alternative is the f-string:
print(f'Well, {name}, I am thinking of a number between 1 and 20.')print(f'Well, {name}, I am thinking of a number between 1 and 20.')
3. Pick a secret number
secretNumber = random.randint(1, 20)secretNumber = random.randint(1, 20)random.randint(1, 20)random.randint(1, 20) returns a random integer from 1 to 20 inclusive — both endpoints are possible.
4. Loop six times
for guessesTaken in range(1, 7):
print('Take a guess. You have ' + str(7 - guessesTaken) + ' guesses left.')
guess = int(input())for guessesTaken in range(1, 7):
print('Take a guess. You have ' + str(7 - guessesTaken) + ' guesses left.')
guess = int(input())range(1, 7)range(1, 7)generates1, 2, 3, 4, 5, 61, 2, 3, 4, 5, 6— six iterations.guessesTakenguessesTakenis the current attempt number.7 - guessesTaken7 - guessesTakengives the player how many tries remain.int(input())int(input())reads a line and converts it to an integer. If the user types"abc""abc", this line will crash — we will fix that in the “Robust Input” section below.
5. Compare and react
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
breakThe three branches cover every possibility:
<<→ too low, keep going.>>→ too high, keep going.- otherwise (
====) → correct,breakbreakout of the loop.
6. Final message
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))If the loop ended because of breakbreak, the player won. Otherwise they ran out of guesses.
Strategy: How Many Guesses Should You Need?
With six guesses for a range of 20, the optimal strategy is binary search — always guess the middle. Each guess halves the remaining range:
| Guess # | Range | Mid |
|---|---|---|
| 1 | 1–20 | 10 |
| 2 | half | 5 or 15 |
| 3 | quarter | … |
| 4–5 | usually solved |
In general you need about log₂(n)log₂(n) guesses for a range of nn numbers. For 1–20 that is about 4.3, so six guesses is generous.
Robust Input
The basic version crashes when the user types letters. Replace int(input())int(input()) with a helper:
def ask_number(prompt, low, high):
while True:
raw = input(prompt)
try:
n = int(raw)
except ValueError:
print("Please enter a whole number.")
continue
if not (low <= n <= high):
print(f"Number must be between {low} and {high}.")
continue
return ndef ask_number(prompt, low, high):
while True:
raw = input(prompt)
try:
n = int(raw)
except ValueError:
print("Please enter a whole number.")
continue
if not (low <= n <= high):
print(f"Number must be between {low} and {high}.")
continue
return nNow guess = ask_number("Your guess: ", 1, 20)guess = ask_number("Your guess: ", 1, 20) handles every bad input gracefully.
Common Mistakes
| Problem | Cause | Fix |
|---|---|---|
ValueError: invalid literal for int()ValueError: invalid literal for int() | User typed letters | Wrap in trytry/except ValueErrorexcept ValueError |
| Loop ends but program says “Nope” even when correct | Used ==== inside the loop without breakbreak | Add breakbreak in the elseelse branch |
Cannot concatenate strstr and intint | 'left: ' + guessesTaken'left: ' + guessesTaken | Convert with str(guessesTaken)str(guessesTaken) or use an f-string |
| Random number is always the same | You set random.seed(0)random.seed(0) somewhere | Remove the seed call for true variability |
Variations to Try
1. Difficulty levels
levels = {"easy": (1, 10, 6), "medium": (1, 50, 7), "hard": (1, 100, 8)}
choice = input("Difficulty (easy/medium/hard): ").lower()
low, high, tries = levels[choice]
secret = random.randint(low, high)levels = {"easy": (1, 10, 6), "medium": (1, 50, 7), "hard": (1, 100, 8)}
choice = input("Difficulty (easy/medium/hard): ").lower()
low, high, tries = levels[choice]
secret = random.randint(low, high)2. Play-again loop
while True:
play_game()
again = input("Play again? (y/n): ").lower()
if again != "y":
breakwhile True:
play_game()
again = input("Play again? (y/n): ").lower()
if again != "y":
break3. Track best score
best = None
# after each round:
if best is None or guessesTaken < best:
best = guessesTaken
print(f"New best score: {best} guesses!")best = None
# after each round:
if best is None or guessesTaken < best:
best = guessesTaken
print(f"New best score: {best} guesses!")4. Persistent high-score file
from pathlib import Path
SCORE_FILE = Path("best_score.txt")
best = int(SCORE_FILE.read_text()) if SCORE_FILE.exists() else None
# update and write back:
if best is None or new_score < best:
SCORE_FILE.write_text(str(new_score))from pathlib import Path
SCORE_FILE = Path("best_score.txt")
best = int(SCORE_FILE.read_text()) if SCORE_FILE.exists() else None
# update and write back:
if best is None or new_score < best:
SCORE_FILE.write_text(str(new_score))5. Reverse the game — you pick, the computer guesses
See the Number Guessing Game with AI project. The AI uses binary search to guess your number in at most seven tries.
6. GUI version with Tkinter
Replace input()input() and print()print() with an entry widget and a label. A few hours of work and you have a clickable game.
Common Interview-Style Questions This Project Touches
- “How would you guess a number between 1 and 1,000,000 with the fewest tries?” → binary search.
- “Why is
int(input())int(input())dangerous?” → invalid user input can crash the program; usetrytry/exceptexcept. - “How does Python’s
randomrandommodule work under the hood?” → Mersenne Twister, pseudo-random.
Real-World Applications
- Game development (loot tables, RNG events, procedural generation).
- Educational tools that teach the binary search algorithm visually.
- A/B testing assignment when you need a random bucket.
- Quick demos of probability concepts in classrooms.
Next Steps
Pick one of the variations above and ship it. Combine two or three for extra credit — for example, difficulty levels + persistent high-score + play-again loop is a complete tiny game. Then move on to projects that combine randomness with state, such as Hangman or Blackjack.
Try it here
The computer picked a secret number from 1–100. Click the bar to guess — it tells you higher or lower and narrows the shaded range until you find it:
Conclusion
You wrote a complete game in roughly fifteen lines of Python, learned how random.randintrandom.randint works, looped with for…rangefor…range, branched with ifif/elifelif/elseelse, and saw how a small program scales up with input validation and replayability. The full source is on GitHub. Find more projects like this on Python Central Hub.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
