How To Code a Simple Number Guessing Game in Python
Tags: python, beginners
Published: 2023-07-27 02:30:28


I spent the last weekend compiling a [list of games you can code in Python](https://sparkian.com/game-you-can-build-in-python/). But why?

If you're a beginner Python programmer, building fun games will help you learn the language faster—and better—without getting bogged down in the syntax and the like. I built some of these games when I was learning Python; I quite enjoyed the process!

The first game you can code—and the simplest of them all—is a **number guessing game** (or Guess the Number!). So I thought I'd write a step-by-step tutorial to code this game—and help beginners learn some of the fundamentals along the way.

Let's begin!

## How Does the Number Guessing Game Work?

In a number guessing game, the user guesses a randomly generated secret number within a given number of attempts. 

After each guess, the user gets hints on whether their guess is too high, too low, or correct. So yeah, the game ends when the user guesses the secret number or runs out of attempts.

## Coding the Number Guessing Game

Let's get to coding! Create a new Python script and code along.

### Step 1 - Import the `random` module

Let's start by importing the built-in [`random`](https://docs.python.org/3/library/random.html) module. The `random` module has functions we can use to generate a random _secret number_ within the specified range:

```python
import random
```

> **Note**: The `random` module gives pseudo-random numbers—and not truly random numbers. So don't use it for sensitive applications such as password generation.

### Step 2 - Set up the range and the maximum number of attempts

Next, we need to decide on the range for the secret number and the maximum number of attempts allowed for the player. For this tutorial, let's set the `lower_bound` and `upper_bound` to 1 and 1000, respectively. Also, set the maximum attempts allowed `max_attempts` to 10:

```python
lower_bound = 1
upper_bound = 1000
max_attempts = 10
```

### Step 3 - Generate a random number

Now, let's generate a random number within the specified range using the `random.randint()` function. This is the secret number that the user needs to guess:

```python
secret_number = random.randint(lower_bound, upper_bound)
```

### Step 4 - Read in the user's input

To get input from the user, let's create a function called `get_guess()`. Remember, the user can enter an invalid input: a number outside the range `[lower_bound, upper_bound]`, a string or a floating point number, and more. 

We handle this in the `get_guess()` function that continuously prompts the user to enter a number—within the specified range—until they provide a valid input. 

Here, we use a `while` loop to prompt the user for a valid input until they enter an integer between `lower_bound` and `upper_bound`:

```python
def get_guess():
    while True:
        try:
            guess = int(input(f"Guess a number between {lower_bound} and {upper_bound}: "))
            if lower_bound <= guess <= upper_bound:
                return guess
            else:
                print("Invalid input. Please enter a number within the specified range.")
        except ValueError:
            print("Invalid input. Please enter a valid number.")
```

### Step 5 - Validate the user's guess

Next, let's define a `check_guess()` function that takes the user's guess and the secret number as inputs and provides feedback on whether the guess is correct, too high, or too low. 

The function compares the player's guess with the secret number and returns a corresponding message:

```python
def check_guess(guess, secret_number):
    if guess == secret_number:
        return "Correct"
    elif guess < secret_number:
        return "Too low"
    else:
        return "Too high"
```

## Step 6 - Track the number of attempts and detect end-of-game conditions

We'll now create the function `play_game()` that handles the game logic and puts everything together. The function uses the `attempts` variable to keep track of the number of attempts made by the user. Within a `while` loop, the user is prompted to enter a guess that's processed by the `get_guess()` function. 

The call to the `check_guess()` function provides feedback on the user's guess:
- If the guess is correct, the user wins, and the game ends.
- Otherwise, the user is given another chance to guess. 
- And this continues until the player guesses the secret number or runs out of attempts.

Here's the `play_game()` function:

```python
def play_game():
    attempts = 0
    won = False

    while attempts < max_attempts:
        attempts += 1
        guess = get_guess()
        result = check_guess(guess, secret_number)

        if result == "Correct":
            print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")
            won = True
            break
        else:
            print(f"{result}. Try again!")

    if not won:
        print(f"Sorry, you ran out of attempts! The secret number is {secret_number}.")

```

### Step 7 - Play the game!

Finally, you can call the `play_game()` function every time the Python script is run:
```python
if __name__ == "__main__":
    print("Welcome to the Number Guessing Game!")
    play_game()
```
### Putting it all together

Now our Python script looks like so:
```python
# main.py
import random

# define range and max_attempts
lower_bound = 1
upper_bound = 1000
max_attempts = 10

# generate the secret number
secret_number = random.randint(lower_bound, upper_bound)

# Get the user's guess
def get_guess():
    while True:
        try:
            guess = int(input(f"Guess a number between {lower_bound} and {upper_bound}: "))
            if lower_bound <= guess <= upper_bound:
                return guess
            else:
                print("Invalid input. Please enter a number within the specified range.")
        except ValueError:
            print("Invalid input. Please enter a valid number.")

# Validate guess
def check_guess(guess, secret_number):
    if guess == secret_number:
        return "Correct"
    elif guess < secret_number:
        return "Too low"
    else:
        return "Too high"

# track the number of attempts, detect if the game is over
def play_game():
    attempts = 0
    won = False

    while attempts < max_attempts:
        attempts += 1
        guess = get_guess()
        result = check_guess(guess, secret_number)

        if result == "Correct":
            print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")
            won = True
            break
        else:
            print(f"{result}. Try again!")

    if not won:
        print(f"Sorry, you ran out of attempts! The secret number is {secret_number}.")

if __name__ == "__main__":
    print("Welcome to the Number Guessing Game!")
    play_game()
```
Here's the output from a sample run of the script:
```
Welcome to the Number Guessing Game!
Guess a number between 1 and 1000: 500
Too low. Try again!
Guess a number between 1 and 1000: 750
Too high. Try again!
Guess a number between 1 and 1000: 625
Too low. Try again!
Guess a number between 1 and 1000: 685
Too low. Try again!
Guess a number between 1 and 1000: 710
Too low. Try again!
Guess a number between 1 and 1000: 730
Congratulations! You guessed the secret number 730 in 6 attempts.
```

## Wrapping Up

Congratulations! You've successfully built a number guessing game in Python. I'll see you all soon in another tutorial. But don't wait for me. Check out [other games you can build](https://sparkian.com/game-you-can-build-in-python/)—features you can code—and start coding!