KAHIBARO Bookshelves
Discord Login Register

17.1. Number guessing game

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 random library
  • 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 random module to pick a random number
  • Allow multiple guesses using a while loop
  • 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 correctly

Points to notice:

  • random.randint(1, 100) gives a random integer between 1 and 100 inclusive.
  • while True: creates a loop that only stops when you break.
  • guesses_taken counts 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.")
        break

Now:

  • 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 a break (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 like f"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!")
        break

Here:

  • 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:

  1. Change the range and attempts
    • Make a version where the number is between 1 and 50 and the player only has 7 attempts.
  2. Guess counter feedback
    • After each guess, also print how many guesses have been used so far (for example: “This was guess 3 of 10”).
  3. 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”.
  4. 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.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms