Python Tutorial - Guessing Game




Hello, this is NanoDano at with the next lesson in this series of Python Cookbook tutorials.

In this lesson we're going to make a game. Personally, I really love game development. I originally learned how to program by teaching myself QBASIC and writing my own video games. The joy of playing of your own games and being able to make them better is a feedback loop of great fun.

Even text-based games can be a lot of fun. These days everyone loves their eye candy, but there are still some text based RPGs called MUDS (or multi user dungeons) that people play.

The game we're going to make is called the guessing game. It will be a building block for larger games to come. The computer will choose a random number betwen 1 and 10, and the user will have three chances to guess it. The computer will tell the user whether their guess was too high or too low.

Create a new python file. Let's name it guessing_game.

Let's start off by greeting the user.

print("Welcome to the guessing game!")

So what do we want to do again? Let's write it out as comments in plain English in the code.

# Computer guesses a random number between 1 and 10

# User guesses the number

# Computer tells user whether guess was too high or too low

# User has 3 guesses before losing the game

There, now we have some place to start. Let's do one thing at a time. Let's generate the random number first.

So far we have seen a few functions that are built in to Python. We saw print, input, and the type function. Python has a large collection of functions grouped in to modules. One of modules that comes with Python by default is the random module. The random module has a bunch of functions related to generating random numbers and shuffling lists.

You can find the documentation for the random module on the website. You can also browse and see what other modules are available. We will be exploring many of them later.

On the documentation page we see a function called randint, and it returns a random integer. That looks exactly like what we need. It shows us that it takes two parameters, a and b.

The random number generated is greater or equal to a and less than or equal to b. So we basically give it a minimum and maximum value and it will return a random number somewhere in that range.

Let's go back to our program and type in what we saw.

random.randint(a, b)

Well, we know we want the number to be between 1 and 10 so let's plug those values in right now.

PyCharm is giving us a hint here with the red squiggles under the word random. Let's mouse over to see what it says. Unresolved reference. We have to import the random module before we use it.

Python does not load the module automatically because it would a lot of unnecessary overhead in terms of memory and speed if Python had to load every module it had even for simple programs. Instead, it will wait until you tell it to load a certain module.

PyCharm makes it easy to do the import. Move the cursor to the word random where the red squiggle is and press alt-enter or select the light bulb to pull up the suggested fixes. Choose "import this name".

Now you will see an import statement at the top of file. Import random, that's all we need to do to tell Python to load the random module and make all the functions available for us.

You might be wondering why we have to put random with a dot in front of our function call to randint(). We have to do this in order to specify that the randint() function we want comes from the random module.

Without the dot, it would look for a function called randint() in our Python script, but we haven't defined one.

This is done to avoid name collision. For example, let's say we also wrote our own function named randint(). We can still use our version by calling randint(), and if we wanted to use the random module's version of randint() we would call it using random.randint().

Without this mechanism, Python would get confused and not know which version of randint() to call, ours or the one from the random module. This also means it is possible for other modules to also defined their own randint() function, if they really wanted to.

We want to store the random number to a variable so in front of the call to random.randint() add correct_answer =.

To test it out, let's print the correct answer and run it a few times.

Looks good.

Now what? Well, let's get the guess from the user. We already know how to do that from the last lesson!

user_guess = input("Guess my number: ")

Now we're going to introduce something new. It is a conditional statement. The If statement.

if user_guess == correct_answer

Can you guess what this does? It's going to compare the user's guess to the correct answer and see if they are equal. Two equal signs mean "check if these two things are equal to each other". Single equal sign, as we have seen, is used to _assign_ a value.

Actually, we need to convert the users input from a string to an integer before we compare these values.

On the line before the if statement but after the input function, write user_guess = int(user_guess). This is going to overwrite the user_guess variable with the integer value. From then on we can use it as an integer instead of a string.

So what do we want to do if this condition is true? if the user guess does equal the correct answer? We want to print out Good guess and you are correct!.

Let's add those print statements now. First, add a colon at the end of the line with the if statement and press enter. Notice it indented the next line for you automatically. Anything that is indented will be run if the if condition is true. Print Good Guess, Print You are correct.

Both of these lines are indented at the same level underneath the if statement. This means both of these lines will get executed if that condition is true.

If this condition is not true, everything indented here will be skipped.

Let's try it.

Nothing happened. We must have guessed wrong. It would be nice to let the user know they guessed wrong.

Instead of just saying _if_ this, _then_ that, you can also say, if this, then that, OTHERWISE, do this.

That is called the else statement. We also have to indent the code that is associated with this condition.

On a new line after the if block, Type else: (indented all the way to the left).

Press enter and on the next line print("Incorrect.")

Let's try it now.

That's better. We must have guessed wrong and therefore the if condition was not true, so it fell through to the else statement and told us we were incorrect.

So now we have the user input and we are giving the user feedback. We were supposed to tell the user whether their guess was too high or too low.

Our if statement already handles the case when the user is correct, but we also want to handle the cases when it is lower or higher separately, instead of all incorrect answers being directed to the generic else statement.

There is another keyword we can use and that is the else if which is written as elif in Python.

Add elif user_guess > correct_answer Sorry, guessed too high

and add elif user_guess < correct_answer Sorry, guessed too low.

It's going to check all of these conditions in the order we wrote them. As soon as the first one is met, all of the other ones will get ignored.

If we are comparing them to see if they are equal and also checking greater than or less than, there is no way that last else statement will ever be reached. A number will always be equal to, greater than or less than another number, so there is no reason for this last else statement any more. Let's get rid of it.

Great, so now we have written the code to do almost all of our tasks to make our game work. It actually works already as a fully functioning game. But, we want to take it one step further, and give the user three chances to guess.

To do that we will need to keep track of how many guesses the user has, so at the top, lets create a variable called number_of_guesses and set it to 3. This will track how many guesses the user has left.

Let's take a second to clean up our code. I don't like the way it is looking right now. I want to move a couple of the comments around and add some blank lines to separate and create readability.

First, let's add a comment to the top where we are printing out the intro and initializing the number of guesses. Let's say "Game set up".

Let's also add a blank line after the section of code that does the game set up for readability.

Then let's take the comment from the bottom that says user guesses the number and move it just above the code that actually does that.

Same thing with the comment about the computer giving a message to the user. Also add a blank line between the user guessing and the response being output just for readability to separate those chunks of code.

Let's move that last comment from the bottom and put it on the line where we define the initial number of guesses.

There, this is much better.

After the user guesses we will want to subtract 1 from the number_of_guesses. After the entire if statement, indented all the way to the left, put number_of_guesses = number_of_guesses - 1. This will decrement or lower the value by one.

PyCharm is trying to give us a hint here with the squiggle. Let's see what it is. Assignment can be replaced with augmented assignment? Let's just click the lightbult and use it's suggestion and replace it with an augmented assignment. Ah, this is a shorthand way of writing the same thing. Minus equal will decrement the value by one.

This is really close, but we have to do one more thing. We have to repeat the guessing process until the number of guesses runs out.

Create a new line above where we ask the user for their input.

add while number_of_guesses > 0:

While is a special keyword that creates a loop. It will keep repeating a block of code as long as the condition is true. In this case, keep repeating and repeating, until the number of guesses is no longer greater than 0. As soon as the number_of_guesses drops down to 0 the while loop will stop running.

So how do we specify WHAT is supposed to get repeated over and over? It is just like we did with the if statement. We have to indent all the code associated with the while statement.

Highlight all of the code involved with the user guessing and being given a response. The whole block of input and the if statement and then press tab.

Now, everyhing indented here will get run in the loop.

There's one problem here though. If we guess the number right, the game does not end. It will keep going if they have more turns left.

We can go in to the if statement where the person guesses correctly and use the break keyword. This will break out of the while loop. It is a special keyword that says I don't care what the conditions are for this loop, I want to get out of it right now! It is not a function, so you do not put parenthesis after it.

We want to add the break after we print out that they guessed correctly.

It would also be nice if it printed out a victory or loss condition at the end. At the very end of the program, after the while loop, indented all the way to the left, let's add if user_won == True:, enter, print("You win")

Also add an else condition that prints you lose.

True and False with capital letters are special values in Python. You may have noticed that we do not have a variable called user_won. So, let's create one!

At the beginning of the file, where we are guessing our number and getting the game set up, let's also create user_won and set it to False.

So by default the user will not win. The only way the user can win is if they guess the number right, so let's go to the if condition where that happens, and at the same time where we print out the "You guessed correct" message, let's also update the user_won variable to be True

That's it. We're done! Give it a run and play it a few times.

The last thing we want to do is commit our changes to the git repo and push the changes to GitHub.

Right click on your root project folder in the project panel and go to Git -> Commit Directory.

Check the box next to the file if it is not already checked. Add a commit message saying "Adding guessing game". Mouse over the commit button and choose commit and push. Finalize the push. All done!

If you liked this video, please subscribe to the channel and share it with your friends. If you haven't watched the earlier videos in this series I recommend you check those out too. Also keep watching the next videos if you want to keep learning Python and building up your cookbook.

Thanks for watching and keep coding.