Play a guessing game in Python

This is a guessing game in Python.

By Katie Cunningham
August 26, 2015

Finally, you have enough coding knowledge to write a simple game! Because this is our first project, let’s go over how this is going to work.

First, I’m going to lay out a plan for you. This plan will include everything our game needs to have in it. Once you read over the plan, you may already have an idea of what the code should look like. If you want to start coding, go right ahead.

Learn faster. Dig deeper. See farther.

Join the O'Reilly online learning platform. Get a free trial today and find answers on the fly, or master something new and useful.

Learn more

If you’re still a little uneasy, though, feel free to move to the next section. There, we’ll have some code for you to work with. It works, so try to play around with it and understand how it’s doing what it’s doing.

Once we have the basic game, I’ll make some suggestions on what you should try adding. Feel free to add whatever you want, or add your own twist to the game.

Finally, I’ll show you my finished code. The final code will have all of the additions that I suggested along the way.

What you need to know…

You should be familiar with everything we’ve gone over until now, but you should be especially comfortable with:

  • Testing for equality
  • Loops
  • if statements
  • Getting input from the user
  • Converting strings into integers

If you’re fuzzy on any of these topics, go back and check out their review videos.

A note for the mentor

You’ve made it to the first project! You also might get to witness your first crisis of confidence in your student. Even a student who has effortlessly raced through each of the previous lesson’s examples might stumble the first time they have to put everything together. Don’t worry! This is common, and students become more confident as they go further in the book.

Guessing games are great for adding personal twists, so once we’re done with the main requirements, feel free to help you student brainstorm ways to make the game even more interesting.

The plan!

We’re going to make a two person guessing game. The first player will type in a number for the second person to guess. If the second person guesses right, then they win! Otherwise, they lose.

Because we’re using two people, we have to make sure that the number the first player enters isn’t seen by the second player. A bunch of print statements should push that off the screen, though.

Here are the components that you’ll have to use to make the basic game:

  • input()
  • int()
  • An if statement
  • Some sort of comparison
  • print()

Once you have your game running, make sure to run it at least twice: Once, where Player One guesses the number, and once where they don’t.

The basic game

This is probably the most simple guessing game you can make. Two people and exactly one guess. Here’s what the code looks like:

secret_num = input("Player One, give me a number: ")

for i in range(100):
    print ("Don't look, Player Two!")

guess = input("Player Two, what's your guess? ")

if guess == secret_num:
    print ("You got it!")
else:
    print ("Sorry, you lose.")

Basically, this code is:

  • Getting a secret number from Player One
  • Printing out a bunch of text to push that number off of the screen
  • Getting a guess from Player Two
  • Checking to see if the guess is equal to the secret number, and printing out a win / lose message

This program is okay, but it’s not very exciting. Let’s add some more features!

Try adding…

Here are some features you might want to add. You can add one, or you can add them all! Just make sure that you add them one at a time. It can be easy to get over-enthusiastic and add a bunch of stuff at once. However, it’s a good idea to run your program each time you add something new. That way, if you get an error, or your program doesn’t work as expected, you only have to look at few lines of code rather than dozens of lines.

Suggested features:

  • Allow Player Two to guess more than once.
  • Allow the players to play another game once the game is over
  • Make sure that the number to guess isn’t bigger than ten
  • Give Player Two hints (like saying that the secret number is bigger or smaller than their guess)

The finished game

Here’s my finished game that builds off of the basic game and incorporates all of the suggested features.

max_num = 10

continue_game = "Y"

while continue_game == "Y":
    while True:
        secret_num = input("Player One, give me a number: ")
        if secret_num.isdigit():
            secret_num = int(secret_num)
            if secret_num > max_num:
                print ("Sorry, the number needs to be less than", max_num)
            else:
                break
        else:
            print ("Sorry, I really need a number")

    for i in range(100):
        print ("Don't look, Player Two!")

    guess = -1

    while guess != secret_num:
        while True:
            guess = input("Player Two, what's your guess? ")
            if guess.isdigit():
                guess = int(guess)
                break
            else:
                print ("Sorry, I really need a number")

        if guess == secret_num:
            print ("You got it!")
        elif guess > secret_num:
            print ("Hmm, that's too big...")
        else:
            print ("Nope, that's too small.")

    continue_game = input("Want another game [Y/N]?")

Let’s go over what each chunk is doing. First, we set up some variables: The largest the secret number can be, and a variable that we’ll be using with the main loop of the game.

max_num = 10

continue_game = "Y"

Next, we start the game. Our first goal is to get a good number to guess! We make Player One enter numbers until we get an integer that’s less than ten.

max_num = 10

continue_game = "Y"
while continue_game == "Y":
    while True:
        secret_num = input("Player One, give me a number: ")
        if secret_num.isdigit():
            secret_num = int(secret_num)
            if secret_num > max_num:
                print ("Sorry, the number needs to be less than", max_num)
            else:
                break
        else:
            print ("Sorry, I really need a number")

Next, we spew out those print statements to push our secret number off the screen.

    for i in range(100):
        print ("Don't look, Player Two!")

Now it’s time for Player Two to guess Player One’s number. First, we set up guess to hold an empty string, so guess != secret_num will work properly (if we don’t set up guess, Python will give us an error).

We need to get a good number out of Player Two, so once again, we keep asking Player Two for numbers until they give us an integer.

guess = -1

    while guess != secret_num:
        while True:
            guess = input("Player Two, what's your guess? ")
            if guess.isdigit():
                guess = int(guess)
                break
            else:
                print ("Sorry, I really need a number")

Once we get a good number, it’s time to see if the two numbers are the same, or if Player Two’s number was too big or too small. If the guess isn’t the same as the secret number, we’ll go back to while guess != secret_num: and get another number out of Player Two.

        if guess == secret_num:
            print ("You got it!")
        elif guess > secret_num:
            print ("Hmm, that's too big...")
        else:
            print ("Nope, that's too small.")

Finally, if Player Two does guess the secret number, we ask if they want to play again. If they enter a capital Y, then we start the game over. If they enter anything else, the game ends.

    continue_game = input("Want another game [Y/N]?")

My code doesn’t look like that!

That’s okay! Your code should work the same. Coding isn’t like doing math, where there’s a limited number of ways to get to the right answer. If you have five developers code the same program, they’ll often do it five different ways.

What’s more important is to understand why my code looks different. Did I do something that was simpler, or did I check for something that you forgot about (like bad input)? Did I simply do something different? Reading other people’s code is a great way to learn tricks that makes your code easier to read, maintain, and run!

Post topics: Open Source
Share:

Get the O’Reilly Radar Trends to Watch newsletter