CODE WITH MARTIN

11. Guessing Game


Let's Make A Game

We now have enough knowledge of Python to start writing applications. Let's put some of our knowledge to the test with a simple number guessing game. This is a great exercise to practice and show how all the things we've learned so far start working together.

I suggest creating a new file in VS Code to put our game code in. I've made a new file called "game.py". We can put all the code we go through below in this new file.

How The Game Works

The game is going to pick a random number between 1 and 10. We will then ask the user to try and guess the number by entering a number in the terminal.

The game will end when the user has guessed the random number. If they don't guess the right number, we'll ask them to try again.

We'll track how many attempts they take to guess the number and also give the user an option to exit the program.

Planning

Before we write code, it's usually a good idea to think of what the behavior of the program is going to be. Then we think about what kind of variables we will need to hold information needed while the game is running.

Looking at how the game works, we've got a couple of things we need store in some variables. The random number we generate will need to be stored in an integer for us to compare against the user guesses.

There is also the number of attempts the user takes to guess, so we'll need another variable tracking how many attempts they have made.

Because we will keep asking the user repeatedly to guess the number, we will probably need some kind of loop.

We'll need to learn how to generate a random number and how we let the user enter a guess. We'll also come up with something the user can enter that will cause the program to end. We'll get to learn how to end a program early.

Time To Code

Let's begin with introducing our game and initializing our variables. This code will be the start of our new game code file:

import sys
import random

print("\n** Welcome to Number Guessing Game **\n")

number = random.randint(1, 10)
attempts = 0

The first 2 lines are special import lines that we'll get to learn in a later section. We need these to be able generate random numbers and exit the program early.

Line 4 is just a welcome message. We've used the new line escape sequence '\n' to make sure the title looks easy to read with line spacing around it.

Line 6, we're defining a variable to hold the random number. We're assigning it using the result of a call to the function 'random.randint'. This function takes two arguments. The first is the lowest number our random can be and the 2nd argument being the highest.

Line 7 is our next variable that we need for tracking the attempts. We'll just set this to 0 for now.

It's now time to let the user know what we've done and what we want them to do in our game. Add these next to lines to our game code:

print("I've thought of a number between 1 and 10.")
print("Enter a number to guess it or type 'x' to exit the program.")

Nice and easy, nothing to explain there.

Next up, is asking the user over and over to take a guess until they get it right. We'll setup the loop and get the user input:

while True:
    guess = input("\nEnter your guess: ")
    attempts += 1

This while loop has a condition that is simply always true. We use the reserved keyword 'True' in Python so that the while loop runs forever. We will control how we exit the loop later in the program.

The 1st line under the while loop is a new variable named 'guess' that will hold our user input. This is assigned to the result of the function call to 'input'. This function causes the terminal to allow the user to enter some text followed by the 'Enter' key.

Because we've allowed the user enter a guess here, we add 1 to the attempts variable.

Now that we have the user input in the 'guess' variable, lets check what they typed. First, lets see if they want to exit by typing the letter 'x'. Here's the loop with this added behavior:

while True:
    guess = input("\nEnter your guess: ")
    attempts += 1
				
    if guess == "x":
        print("Thanks for playing.")
        sys.exit()

We use an if statement to compare the value in the guess variable with the string "x". If that's true (it matches), we run the print statement to say thanks for playing, followed by a line to a special function 'sys.exit()' that causes the Python program to end.

Now let's check the number they entered, here's the while loop extended:

while True:
    guess = input("\nEnter your guess: ")
    attempts += 1

    if guess == "x":
        print("Thanks for playing.")
        sys.exit()
    elif not guess.isnumeric():
        print("You must enter a number between 1 and 10.")
        continue

We've introduced a 'elif' check to test the guess variable again to see if it's a number. We do this by using the string function named 'isnumeric'. This is a really handy function that tell us True or False if the string contains a valid number. We also use the 'not' keyword because we want to know that if its not a number, we want to print a warning to the user. After the warning, we use the 'continue' statement to make the while loop start again at the top.

We need another check to see if the user guessed the number. Here's the while loop extended again:

while True:
    guess = input("\nEnter your guess: ")
    attempts += 1

    if guess == "x":
        print("Thanks for playing.")
        sys.exit()
    elif not guess.isnumeric():
        print("You must enter a number between 1 and 10.")
        continue
    elif int(guess) == number:
        print("Nice! You guessed my number in {} tries!".format(attempts))
        print("Thanks for playing.")
        sys.exit()

On the line of the new 'elif' statement, we use the Python function 'int' to convert the 'guess' variable to an integer before comparing it with the '==' operator. We do this because the 'guess' variable when assigned from the 'input' function is a string and Python needs both values to be integers when comparing two integers together.

Notice how our first print statement makes used of a placeholder '{}' and the string function 'format' to replace the placeholder with our 'attempts' variable.

We also use the 'sys.exit()' function to exit the program after telling the user they guessed correctly.

Finally, we need to do something for when they didn't guess the correct number. Here's the extended while loop again:

while True:
    guess = input("\nEnter your guess: ")
    attempts += 1

    if guess == "x":
        print("Thanks for playing.")
        sys.exit()
    elif not guess.isnumeric():
        print("You must enter a number between 1 and 10.")
        continue
    elif int(guess) == number:
        print("Nice! You guessed my number in {} tries!".format(attempts))
        print("Thanks for playing.")
        sys.exit()
    else:
        print("That wasn't the number, try again.")

This final else statement executes if the above conditions in the if statement all fail, which looking at all the things we checked for, the only thing left is that the user didn't guess the number. After this else statement runs, the while loop will iterate and start again at the top of the while loop, which causes us to go through the cycle of asking the user to guess again and performing all of our checks.

Finished

We're done! Here's what your entire game code file should look like in it's complete form:

import sys
import random

print("\n** Welcome to Number Guessing Game **\n")

number = random.randint(1, 10)
attempts = 0

print("I've thought of a number between 1 and 10.")
print("Enter a number to guess it or type 'x' to exit the program.")

while True:
    guess = input("\nEnter your guess: ")
    attempts += 1

    if guess == "x":
        print("Thanks for playing.")
        sys.exit()
    elif not guess.isnumeric():
        print("You must enter a number between 1 and 10.")
        continue
    elif int(guess) == number:
        print("Nice! You guessed my number in {} tries!".format(attempts))
        print("Thanks for playing.")
        sys.exit()
    else:
        print("That wasn't the number, try again.")

A beautiful 27 lines of Python code for your first ever number guessing game. I hope you enjoyed making this. It takes me back to the very first time I wrote something like this when I was first learning and how excited I was to see it working. Give yourself a big pat on the back.

Challenge

Try and change the game so that you only have 5 attempts to guess the number. Before you enter a guess, tell the user how many attempts they have remaining. If they run out of attempts, print a message to the user saying the game is over because they ran out of guesses and end the program.