Table of Contents
Overview
In this mini project, you’ll build a number guessing game in Python.
The idea:
- The computer picks a random secret number.
- The player guesses the number.
- The program tells the player whether the guess is too high, too low, or correct.
- The game continues until the player guesses correctly (or runs out of attempts, if you choose to add a limit).
This project practices:
- User input and output
if/elif/else- Loops
- Random numbers with the
randomlibrary - Basic program design
You’ll see several versions, from simple to slightly more advanced.
Version 1: A Very Simple Guessing Game
This first version has:
- A secret number you choose yourself in the code
- One guess from the user
- A simple success / failure message
# Very simple number guessing game
secret_number = 7 # you can change this
guess = int(input("Guess the number: "))
if guess == secret_number:
print("Correct! You guessed the number.")
else:
print("Sorry, that's not correct.")This is not very fun yet: the user only gets one guess and the number never changes. Next, you’ll improve it.
Version 2: Random Secret Number and Unlimited Guesses
Now you’ll:
- Use the
randommodule to pick a random number - Allow multiple guesses using a
whileloop - Give hints: “too high” or “too low”
import random
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
secret_number = random.randint(1, 100) # random number from 1 to 100
guesses_taken = 0
while True:
guess_text = input("Take a guess: ")
# Convert input to an integer
guess = int(guess_text)
guesses_taken = guesses_taken + 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("Correct! You guessed the number.")
print("You took", guesses_taken, "guesses.")
break # exit the loop when guessed correctlyPoints to notice:
random.randint(1, 100)gives a random integer between 1 and 100 inclusive.while True:creates a loop that only stops when youbreak.guesses_takencounts how many guesses the player needed.
Handling Invalid Input
Right now, if the player types something that’s not a number (like hello), the program will crash. Let’s handle that more safely.
You can use try / except to catch errors when converting input to an int.
import random
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
secret_number = random.randint(1, 100)
guesses_taken = 0
while True:
guess_text = input("Take a guess: ")
# Try to convert input to a number
try:
guess = int(guess_text)
except ValueError:
print("That is not a valid number. Please enter a whole number.")
continue # go back to the top of the loop
# Optional: check if the guess is in the valid range
if guess < 1 or guess > 100:
print("Please guess a number between 1 and 100.")
continue
guesses_taken = guesses_taken + 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("Correct! You guessed the number in", guesses_taken, "guesses.")
breakNow:
- Invalid input doesn’t crash the game.
- The player is reminded to stay within the correct range.
Version 3: Limiting the Number of Attempts
To make the game more challenging, you can:
- Limit how many guesses the player gets
- Tell the player if they’ve lost after using all attempts
For example, allow 10 guesses:
import random
MAX_ATTEMPTS = 10 # use a constant to make it easy to change later
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
print("You have", MAX_ATTEMPTS, "attempts to guess it.")
secret_number = random.randint(1, 100)
guesses_taken = 0
while guesses_taken < MAX_ATTEMPTS:
guess_text = input("Guess (" + str(MAX_ATTEMPTS - guesses_taken) + " attempts left): ")
try:
guess = int(guess_text)
except ValueError:
print("Please enter a valid whole number.")
continue
if guess < 1 or guess > 100:
print("Your guess must be between 1 and 100.")
continue
guesses_taken = guesses_taken + 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("Correct! You guessed the number in", guesses_taken, "guesses.")
break
else:
# This 'else' belongs to the 'while', not to 'if'
print("Sorry, you ran out of attempts. The number was", secret_number)Key idea:
while guesses_taken < MAX_ATTEMPTS:stops the loop after too many guesses.- The
while ... else:part runs if the loop ended without abreak(the player never guessed correctly).
Adding Difficulty Levels
You can let the player choose how hard the game is by changing:
- The range of numbers (for example 1–10 vs 1–1000)
- The number of attempts
Example using three difficulty levels:
import random
print("Number Guessing Game")
print("Choose a difficulty level:")
print("1 - Easy (1 to 10, 5 attempts)")
print("2 - Medium (1 to 100, 10 attempts)")
print("3 - Hard (1 to 1000, 12 attempts)")
choice = input("Enter 1, 2, or 3: ")
if choice == "1":
min_number = 1
max_number = 10
max_attempts = 5
elif choice == "2":
min_number = 1
max_number = 100
max_attempts = 10
else:
# Default to hard if anything else is entered
min_number = 1
max_number = 1000
max_attempts = 12
secret_number = random.randint(min_number, max_number)
guesses_taken = 0
print(f"\nI'm thinking of a number between {min_number} and {max_number}.")
print(f"You have {max_attempts} attempts.")
while guesses_taken < max_attempts:
guess_text = input("Your guess: ")
try:
guess = int(guess_text)
except ValueError:
print("Please enter a whole number.")
continue
if guess < min_number or guess > max_number:
print(f"Stay within {min_number} and {max_number}.")
continue
guesses_taken += 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print(f"Correct! You guessed the number in {guesses_taken} guesses.")
break
if guesses_taken == max_attempts and guess != secret_number:
print(f"You've used all attempts. The number was {secret_number}.")This version introduces:
- Simple game configuration based on user choice
f-strings likef"You have {max_attempts} attempts."for cleaner formatting
Adding a Play-Again Loop
You can wrap the whole game in another loop so that the player can choose to play again without restarting the program.
import random
def play_game():
secret_number = random.randint(1, 100)
max_attempts = 10
guesses_taken = 0
print("\nI'm thinking of a number between 1 and 100.")
print("You have", max_attempts, "attempts.")
while guesses_taken < max_attempts:
guess_text = input("Your guess: ")
try:
guess = int(guess_text)
except ValueError:
print("Please enter a whole number.")
continue
if guess < 1 or guess > 100:
print("Your guess must be between 1 and 100.")
continue
guesses_taken += 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("Correct! You guessed the number in", guesses_taken, "guesses.")
return # end the function when the player wins
print("You ran out of attempts. The number was", secret_number)
print("Welcome to the Number Guessing Game!")
while True:
play_game()
again = input("\nDo you want to play again? (y/n): ").lower()
if again != "y":
print("Thanks for playing. Goodbye!")
breakHere:
- The game logic is in a function
play_game(). - The outer
while True:loop repeats the game until the player chooses to stop.
Extra Ideas to Improve Your Game
Once the basic game works, you can experiment with:
- Scoring
- Fewer guesses = higher score
- Add bonus points on higher difficulties
- Hints
- After every wrong guess, say whether the player is “warm” or “cold” based on how close they are
- Example: “within 10 of the number”
- Secret debug mode
- If the player types a special word (e.g.
cheat), show the secret number (useful when you’re debugging) - Better messages
- Different messages when the player is very close
- Different output for winning on the first guess
- Custom range
- Let the user choose the minimum and maximum number at the start
These additions use the same basic building blocks you’ve already used: input, conditions, loops, and simple math.
Practice Exercises
Try these small tasks to strengthen your understanding:
- Change the range and attempts
- Make a version where the number is between 1 and 50 and the player only has 7 attempts.
- Guess counter feedback
- After each guess, also print how many guesses have been used so far (for example: “This was guess 3 of 10”).
- Close-guess hint
- If the player’s guess is within 5 of the secret number, print a message like “Very close!” in addition to “Too high” or “Too low”.
- Reverse roles (optional)
- Make a different game where the computer tries to guess your number (you’ll need loops and conditions for this).
All of these variations build on the same basic number guessing game, and they are great practice to become more comfortable with Python.