Project 3: Guess the Number
This is your third final project option. Guess the Number is a
deceptively simple game that exercises your understanding of loops,
conditionals, functions, input validation and the
random module. It is a great project for solidifying
the core concepts before moving on to more complex programs.
The computer picks a random number. The player has a limited number of attempts to guess it. After each guess the game tells the player whether to guess higher or lower. You will build it step by step until you have a fully working game.
What You Will Build
Your finished game will:
- Generate a random number between 1 and 100 using the
randommodule - Give the player a limited number of attempts based on the difficulty they choose
- Tell the player to guess higher or lower after each incorrect guess
- Track the number of attempts used
- Display a win or loss message at the end
- Show the player their best score across multiple games
- Ask the player if they want to play again
Concepts You Will Use
- random to generate the secret number
- Functions to organise the game into reusable blocks
- While loops to keep the game running
- Conditionals to give higher or lower hints and check for a win
- input() and type conversion to handle player guesses
- f-strings to display game information clearly
- global to track the best score across games
- Scope to understand where each variable lives
Step 1 — Set Up Your File
Create a new file in VS Code named guess_the_number.py in your final project folder. Add the following at the top:
# Python Essentials - Final Project
# Guess the Number Game
# Your name here
import random
best_score = None
best_score = None is a global variable that will track
the fewest attempts the player has ever used to win. It starts as
None because no game has been played yet.
Step 2 — Choose a Difficulty
Add a function called choose_difficulty() that asks the
player to pick a difficulty and returns the number of attempts allowed.
def choose_difficulty():
'''
Asks the player to choose a difficulty level.
Returns: an integer representing the number of attempts allowed.
'''
print("\nChoose a difficulty:")
print(" 1. Easy - 10 attempts")
print(" 2. Medium - 7 attempts")
print(" 3. Hard - 5 attempts")
while True:
choice = input("\nEnter 1, 2 or 3: ").strip()
if choice == "1":
return 10
elif choice == "2":
return 7
elif choice == "3":
return 5
else:
print("Please enter 1, 2 or 3.")
Step 3 — Get a Valid Guess
Add a function called get_guess() that asks the player
for a number and validates it before returning it. This handles cases
where the player types something that is not a number.
def get_guess():
'''
Asks the player to enter a number between 1 and 100.
Validates the input and keeps asking until a valid number is entered.
Returns: an integer between 1 and 100.
'''
while True:
try:
guess = int(input("Enter your guess (1-100): "))
if 1 <= guess <= 100:
return guess
else:
print("Please enter a number between 1 and 100.")
except ValueError:
print("That is not a valid number. Try again.")
The try / except block handles the case where the player
types something that cannot be converted to an integer. This is your
first look at error handling in Python.
Step 4 — Display the Welcome Message
Add a function called show_welcome() that prints a
welcome message when the game starts.
def show_welcome():
print("=" * 40)
print(" PYTHON ESSENTIALS: GUESS THE NUMBER")
print("=" * 40)
print("I am thinking of a number between 1 and 100.")
print("Can you guess it?")
print("=" * 40)
Step 5 — Build the Main Game Loop
Add a function called play_game() that runs one full
game. This is where all the pieces come together.
def play_game():
global best_score
secret_number = random.randint(1, 100)
max_attempts = choose_difficulty()
attempts = 0
print(f"\nOK. I have picked a number. You have {max_attempts} attempts.")
while attempts < max_attempts:
attempts += 1
remaining = max_attempts - attempts
guess = get_guess()
if guess == secret_number:
print(f"\n{'=' * 40}")
print(f" Correct! The number was {secret_number}.")
print(f" You got it in {attempts} attempt{'s' if attempts != 1 else ''}.")
if best_score is None or attempts < best_score:
best_score = attempts
print(f" New best score: {best_score} attempt{'s' if best_score != 1 else ''}!")
else:
print(f" Your best score is still {best_score} attempt{'s' if best_score != 1 else ''}.")
print(f"{'=' * 40}")
return
elif guess < secret_number:
print(f"Too low! ", end="")
else:
print(f"Too high! ", end="")
if remaining > 0:
print(f"You have {remaining} attempt{'s' if remaining != 1 else ''} remaining.")
else:
print()
print(f"\n{'=' * 40}")
print(f" Out of attempts! The number was {secret_number}.")
print(f"{'=' * 40}")
Step 6 — Ask to Play Again
Add the same ask_play_again() function used in the
other projects.
def ask_play_again():
while True:
choice = input("\nPlay again? (yes / no): ").lower().strip()
if choice == "yes":
return True
elif choice == "no":
return False
else:
print("Please type yes or no.")
Step 7 — Wire It All Together
Add the main() function and call it at the bottom of
the file.
def main():
show_welcome()
while True:
play_game()
if best_score is not None:
print(f"\nYour best score this session: {best_score} attempt{'s' if best_score != 1 else ''}.")
if not ask_play_again():
print("\nThanks for playing. Goodbye!")
break
main()
The Complete Game
Here is the full completed game for reference. Only look at this after you have tried building it yourself.
# Python Essentials - Final Project
# Guess the Number Game
# Your name here
import random
best_score = None
def choose_difficulty():
print("\nChoose a difficulty:")
print(" 1. Easy - 10 attempts")
print(" 2. Medium - 7 attempts")
print(" 3. Hard - 5 attempts")
while True:
choice = input("\nEnter 1, 2 or 3: ").strip()
if choice == "1":
return 10
elif choice == "2":
return 7
elif choice == "3":
return 5
else:
print("Please enter 1, 2 or 3.")
def get_guess():
while True:
try:
guess = int(input("Enter your guess (1-100): "))
if 1 <= guess <= 100:
return guess
else:
print("Please enter a number between 1 and 100.")
except ValueError:
print("That is not a valid number. Try again.")
def show_welcome():
print("=" * 40)
print(" PYTHON ESSENTIALS: GUESS THE NUMBER")
print("=" * 40)
print("I am thinking of a number between 1 and 100.")
print("Can you guess it?")
print("=" * 40)
def play_game():
global best_score
secret_number = random.randint(1, 100)
max_attempts = choose_difficulty()
attempts = 0
print(f"\nOK. I have picked a number. You have {max_attempts} attempts.")
while attempts < max_attempts:
attempts += 1
remaining = max_attempts - attempts
guess = get_guess()
if guess == secret_number:
print(f"\n{'=' * 40}")
print(f" Correct! The number was {secret_number}.")
print(f" You got it in {attempts} attempt{'s' if attempts != 1 else ''}.")
if best_score is None or attempts < best_score:
best_score = attempts
print(f" New best score: {best_score} attempt{'s' if best_score != 1 else ''}!")
else:
print(f" Your best score is still {best_score} attempt{'s' if best_score != 1 else ''}.")
print(f"{'=' * 40}")
return
elif guess < secret_number:
print(f"Too low! ", end="")
else:
print(f"Too high! ", end="")
if remaining > 0:
print(f"You have {remaining} attempt{'s' if remaining != 1 else ''} remaining.")
else:
print()
print(f"\n{'=' * 40}")
print(f" Out of attempts! The number was {secret_number}.")
print(f"{'=' * 40}")
def ask_play_again():
while True:
choice = input("\nPlay again? (yes / no): ").lower().strip()
if choice == "yes":
return True
elif choice == "no":
return False
else:
print("Please type yes or no.")
def main():
show_welcome()
while True:
play_game()
if best_score is not None:
print(f"\nYour best score this session: {best_score} attempt{'s' if best_score != 1 else ''}.")
if not ask_play_again():
print("\nThanks for playing. Goodbye!")
break
main()
Challenges — Take It Further
Challenge 1 — Narrow the Range
- After each incorrect guess display the current valid range
- For example after a too low guess of 30 show "Guess between 31 and 100"
- Track the lower and upper bounds as variables and update them after each guess
Challenge 2 — Multiplayer
- Ask for two player names at the start
- Alternate turns between the two players
- The first player to guess correctly wins the round
- Track wins across multiple rounds
Challenge 3 — Reverse Mode
- The player thinks of a number and the computer tries to guess it
- The player tells the computer higher, lower or correct after each guess
- The computer uses a binary search strategy to guess efficiently
Challenge 4 — Session Statistics
- Track total games played, total wins and total losses across the session
- Display a full statistics summary when the player chooses to quit
- Calculate and display the win percentage
What You Just Demonstrated
By completing this project you have shown you can:
- Import and use the
randommodule - Validate user input and handle type conversion errors
- Use the
globalkeyword to track state across function calls - Structure a program using multiple focused functions
- Use
while Truewithbreakandreturnto control flow - Give the player meaningful feedback on every action
- Handle singular and plural grammar dynamically using ternary expressions
- Build a complete interactive game from scratch
That is not a beginner skill set anymore.
Don't Forget to commit and Push!