Guess the Number Game: Build a Fun Interactive Project

Introduction

In this chapter, you will build a complete "Guess the Number" game in Python. The program generates a random number from 1 to 100, then guides the user to guess it with hints. This mini project combines loops, conditions, lists, and user interaction into one practical script.

Prerequisites

  • Python 3.10+ installed
  • Basic understanding of variables, loops, conditions, and lists
  • Ability to run .py files in terminal or IDE

Project Goal

Build a game with these rules:

  • Generate one random integer between 1 and 100
  • Let the user guess repeatedly
  • After each guess, print Too high or Too low
  • If correct, print:
    • success message
    • total attempts used
    • all previous guesses

This is a great beginner project because it feels like a real game while training core programming logic.

1) Import Random and Generate Secret Number

Use Python's built-in random module.

python
# Import random tools
import random
 
# Generate random integer in range [1, 100]
secret_number = random.randint(1, 100)
 
# Debug print (optional during development)
# print(secret_number)

2) Prepare Tracking Variables

We need to record guess history and attempt count.

python
# Store all user guesses
guess_history = []
 
# Count attempts
attempts = 0

3) Core Game Loop

Use while True to keep asking until the answer is correct.

python
# Repeat until user guesses correctly
while True:
    # Read one guess from user
    guess = int(input("Guess a number between 1 and 100: "))
 
    # Update counters
    attempts += 1
    guess_history.append(guess)
 
    # Compare guess and secret number
    if guess < secret_number:
        print("Too low.")
    elif guess > secret_number:
        print("Too high.")
    else:
        print("Correct! You guessed it.")
        break

Tip

Good Learning Habit

Keep a guess_history list so you can review game behavior and practice list operations.

4) Print Final Summary

After the loop ends, show complete result information.

python
# Print final result summary
print(f"Total attempts: {attempts}")
print(f"Your guesses: {guess_history}")

5) Full Runnable Version

Here is the complete script based on the project requirement.

python
# Import random tools
import random
 
# Generate random integer in range [1, 100]
secret_number = random.randint(1, 100)
 
# Store all user guesses
guess_history = []
 
# Count attempts
attempts = 0
 
# Repeat until user guesses correctly
while True:
    try:
        # Read one guess from user
        guess = int(input("Guess a number between 1 and 100: "))
    except ValueError:
        # Handle invalid numeric input
        print("Please enter a valid integer.")
        continue
 
    # Validate range
    if guess < 1 or guess > 100:
        print("Out of range. Please enter a number from 1 to 100.")
        continue
 
    # Update counters
    attempts += 1
    guess_history.append(guess)
 
    # Compare guess and secret number
    if guess < secret_number:
        print("Too low.")
    elif guess > secret_number:
        print("Too high.")
    else:
        print(f"Correct! The number was {secret_number}.")
        print(f"You used {attempts} attempts.")
        print(f"Guess history: {guess_history}")
        break

6) Optional Upgrade Ideas

After finishing the base version, try these upgrades:

  • Add difficulty modes (1-50, 1-100, 1-500)
  • Limit max attempts
  • Ask whether user wants to replay
  • Show best score (fewest attempts)

Warning

Avoid counting invalid input as a valid attempt unless you intentionally design the rules that way.

Common Beginner Mistakes

Mistake 1: Forgetting to Update Attempt Counter

If attempts += 1 is missing, your summary will be wrong.

Mistake 2: Not Handling Non-Numeric Input

Typing text like abc causes ValueError unless handled with try/except.

Mistake 3: Losing Guess History

If you forget guess_history.append(guess), you cannot display past guesses at the end.

Surprise Practice Challenge

Create a "smart hint" version:

  1. Keep current game logic
  2. After each wrong guess, also print distance hint:
    • Very close if difference <= 3
    • Close if difference <= 10
    • Far otherwise
  3. At the end, print the best guess (closest value)

If you finish this, you are already combining game logic with lightweight analytics.

FAQ

Why use random.randint(1, 100)?

It returns an integer and includes both endpoints (1 and 100), which matches the game requirement.

Should invalid input increase attempts?

It depends on your game design. Most beginner-friendly versions do not count invalid input.

Why store all guesses in a list?

It supports post-game summary, debugging, and future features like closest-guess analysis.

Can I build this with functions?

Yes. Splitting into functions like read_guess(), compare_guess(), and print_summary() is a good next step.