Skip to content
Python project #02Beginner

Number Guessing Game

Guess a secret number with higher/lower hints, warmth clues, limited attempts, replays and a best score — repeatable with a seed.

Estimated time
~2 hours to build
Files
4 files · 251 lines
Technologies
Python 3, random.Random, input()

Introduction

The guessing game is a classic first project because it combines a loop, input validation, conditions and a little randomness. This version adds warmth hints, ignores repeated guesses and keeps a best score across rounds.

Problem statement

Pick a secret number from 1 to 100. Give the player seven attempts, saying whether to go higher or lower and how close they are. Reject non-numbers and out-of-range numbers without using up an attempt, and don't count repeated guesses. After each round, offer to play again; at the end show games played, wins and the best score. An optional seed makes the secret numbers repeatable for testing.

Objectives

  • Write a game loop with while and break
  • Validate user input without crashing
  • Use random.Random with a seed for repeatable behaviour
  • Track state across rounds

Features

  • Higher/lower hints with very hot / warm / cold clues
  • Seven attempts; invalid and repeated guesses don't count
  • Play-again loop with wins and best score
  • Optional seed for repeatable games
  • Clean exit when input ends

Concepts demonstrated

  • Game loops
  • Input validation
  • Seeded random numbers
  • Functions returning optional values

System architecture

ask wraps input() and echoes the line when input comes from a file, so test transcripts are readable. play_round runs one game and returns the attempts used on a win or None. hint builds the higher/lower message with a warmth clue based on the distance. main reads the seed, creates a random.Random and loops over rounds while tracking wins and the best score.

Folder structure

TextProject tree
number-guessing-game/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

85 lines
Pythonmain.py
"""Number Guessing Game with hints, limited attempts, replays and a best score.
Type a seed at the start to make the secret numbers repeatable (useful for testing),
or press Enter for a random game.
"""
import random
import sys
LOW, HIGH, MAX_ATTEMPTS = 1, 100, 7
def ask(prompt: str) -> str | None:
"""Read one line; echo it when input comes from a file so transcripts stay readable."""
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip()
def hint(guess: int, secret: int) -> str:
direction = "higher" if guess < secret else "lower"
gap = abs(guess - secret)
warmth = "very hot" if gap <= 3 else "warm" if gap <= 10 else "cold"
return f"Go {direction} ({warmth})."
def play_round(rng: random.Random) -> int | None:
"""Play one round. Returns attempts used on a win, None on a loss or when input ends."""
secret = rng.randint(LOW, HIGH)
tried: list[int] = []
print(f"I'm thinking of a number between {LOW} and {HIGH}. You have {MAX_ATTEMPTS} attempts.")
while len(tried) < MAX_ATTEMPTS:
answer = ask(f"Guess #{len(tried) + 1}: ")
if answer is None:
return None
if not answer.lstrip("-").isdigit():
print("Please enter a whole number.")
continue
guess = int(answer)
if not LOW <= guess <= HIGH:
print(f"Stay between {LOW} and {HIGH}.")
continue
if guess in tried:
print(f"You already tried {guess}; that one doesn't count.")
continue
tried.append(guess)
if guess == secret:
print(f"Correct! {secret} found in {len(tried)} attempt{'s' if len(tried) > 1 else ''}.")
return len(tried)
print(hint(guess, secret), f"Attempts left: {MAX_ATTEMPTS - len(tried)}.")
print(f"Out of attempts. The number was {secret}.")
return None
def main() -> None:
seed_text = ask("Seed (press Enter for a random game): ")
if seed_text is None:
return
rng = random.Random(int(seed_text)) if seed_text.lstrip("-").isdigit() else random.Random()
games = wins = 0
best: int | None = None
while True:
games += 1
print(f"\n--- Game {games} ---")
result = play_round(rng)
if result is not None:
wins += 1
if best is None or result < best:
best = result
print("New best score!")
again = ask("Play again? (y/n): ")
if again is None or again.lower() not in ("y", "yes"):
break
print(f"\nGames played: {games}, won: {wins}, best: {best if best is not None else '-'} attempts")
if __name__ == "__main__":
main()

What each file does

main.py
The whole program: data classes, validation, the command loop and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Seed (press Enter for a random game): 7
--- Game 1 ---
I'm thinking of a number between 1 and 100. You have 7 attempts.
Guess #1: 50
Go lower (warm). Attempts left: 6.
Guess #2: abc
Please enter a whole number.
Guess #2: 150
Stay between 1 and 100.
Guess #2: 25
Go higher (cold). Attempts left: 5.
Guess #3: 37
Go higher (warm). Attempts left: 4.
Guess #4: 45
Go lower (very hot). Attempts left: 3.
Guess #5: 42
Correct! 42 found in 5 attempts.
New best score!
Play again? (y/n): y
--- Game 2 ---
I'm thinking of a number between 1 and 100. You have 7 attempts.
Guess #1: 50
Go lower (cold). Attempts left: 6.
Guess #2: 30
Go lower (warm). Attempts left: 5.
Guess #3: 10
Go higher (warm). Attempts left: 4.
Guess #4: 15
Go higher (warm). Attempts left: 3.
Guess #5: 15
You already tried 15; that one doesn't count.
Guess #5: 25
Go lower (warm). Attempts left: 2.
Guess #6: 18
Go higher (very hot). Attempts left: 1.
Guess #7: 19
Go higher (very hot). Attempts left: 0.
Out of attempts. The number was 20.
Play again? (y/n): n
Games played: 2, won: 1, best: 5 attempts
Input
7
50
abc
150
25
37
45
42
y
50
30
10
15
15
25
18
19
n

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • Seed 7 makes the secrets 42 and then 20.
  • In game 1, 'abc' and 150 are rejected without costing an attempt, and 42 is found on the fifth attempt.
  • In game 2 the repeated guess 15 doesn't count, and after seven attempts the number 20 is revealed.

Common errors

ValueError when the player types a word

Check answer.isdigit() before calling int(), and ask again.

The same numbers appear every game

Only pass a seed for testing; random.Random() without a seed uses fresh randomness.

Possible improvements

  • Add difficulty levels with different ranges and attempt limits
  • Save the best score to a file between runs
  • Show the optimal number of guesses (binary search) after each round

Additional challenges

  1. 1Let the computer guess your number using binary search.
  2. 2Add a two-player mode where one player sets the number.
  3. 3Give a score that depends on attempts and time taken.

Built and tested it yourself? Mark it to update your dashboard.