Skip to content

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 between aa and bb, inclusive.
  • forfor loop with rangerange — iterates a fixed number of times.
  • ifif/elifelif/elseelse — choose between several branches.
  • breakbreak — exit a loop immediately.
  • Type conversionint(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

  1. Make a folder named guess-the-numberguess-the-number.
  2. Inside it, create a file named guessthenumber.pyguessthenumber.py.
  3. Open the folder in your editor.

Write the code

Paste the following into guessthenumber.pyguessthenumber.py:

Guess The NumberSource
Guess The Number
# 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
# 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:

command
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.
command
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

guessthenumber.py
import random
guessthenumber.py
import random

The randomrandom module is part of Python’s standard library. After this line, random.randint(...)random.randint(...) is available.

2. Greet the user

guessthenumber.py
print('Hello, what is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 and 20.')
guessthenumber.py
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

guessthenumber.py
secretNumber = random.randint(1, 20)
guessthenumber.py
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

guessthenumber.py
for guessesTaken in range(1, 7):
    print('Take a guess. You have ' + str(7 - guessesTaken) + ' guesses left.')
    guess = int(input())
guessthenumber.py
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) generates 1, 2, 3, 4, 5, 61, 2, 3, 4, 5, 6 — six iterations.
  • guessesTakenguessesTaken is the current attempt number.
  • 7 - guessesTaken7 - guessesTaken gives 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

guessthenumber.py
    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')
    else:
        break
guessthenumber.py
    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')
    else:
        break

The three branches cover every possibility:

  • << → too low, keep going.
  • >> → too high, keep going.
  • otherwise (====) → correct, breakbreak out of the loop.

6. Final message

guessthenumber.py
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))
guessthenumber.py
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 #RangeMid
11–2010
2half5 or 15
3quarter
4–5usually 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:

safe_input.py
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 n
safe_input.py
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 n

Now guess = ask_number("Your guess: ", 1, 20)guess = ask_number("Your guess: ", 1, 20) handles every bad input gracefully.

Common Mistakes

ProblemCauseFix
ValueError: invalid literal for int()ValueError: invalid literal for int()User typed lettersWrap in trytry/except ValueErrorexcept ValueError
Loop ends but program says “Nope” even when correctUsed ==== inside the loop without breakbreakAdd breakbreak in the elseelse branch
Cannot concatenate strstr and intint'left: ' + guessesTaken'left: ' + guessesTakenConvert with str(guessesTaken)str(guessesTaken) or use an f-string
Random number is always the sameYou set random.seed(0)random.seed(0) somewhereRemove the seed call for true variability

Variations to Try

1. Difficulty levels

difficulty.py
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)
difficulty.py
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

replay.py
while True:
    play_game()
    again = input("Play again? (y/n): ").lower()
    if again != "y":
        break
replay.py
while True:
    play_game()
    again = input("Play again? (y/n): ").lower()
    if again != "y":
        break

3. Track best score

best.py
best = None
# after each round:
if best is None or guessesTaken < best:
    best = guessesTaken
    print(f"New best score: {best} guesses!")
best.py
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

persist.py
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))
persist.py
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; use trytry/exceptexcept.
  • “How does Python’s randomrandom module 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:

sketch Guess the number (1-100) p5.js
Click the bar to guess. The game says higher or lower and narrows the range until you win.

Conclusion

You wrote a complete game in roughly fifteen lines of Python, learned how random.randintrandom.randint works, looped with forrangeforrange, 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 coffee

Was this page helpful?

Let us know how we did