Howdy folks welcome to this python beginners tutorial. In this tutorial, you will learn how to build a random number guessing game in python3. This is an excellent python project, especially for absolute beginners.

You can download the final complete project code here from my Github repo - https://github.com/the-coding-pie/guess-the-number-python3

Now, without further ado, let's get started...

The Game Plan

Guess the Number/Number Guessing Game is a classic game where some random number will be generated by the computer between the lower limit and upper limit (eg: 1 to 20), and the user had to keep guessing numbers until the user finds the computer's number, and the computer will tell you each time if your guess was too high or too low: Once you've correctly guessed the number, the computer will say "You guessed it right!".

To add a little bit thrill to the game, here we are going to give the user only 5 chances to guess the random number! If the user failed to guess the number correctly then the computer will say "You lose!" and reveal the number.

Here is the step by step complete breakdown of our number guessing game which we are going to build. If you want to try it on your own and want a little bit of adventure, then hey just do it with the help of the following steps:

  1. First, import the random module.
  2. Then generate a random integer between 1 to 20 (including both numbers) and store it in a variable called secret_number.
  3. Then create a variable called chances_left and assign it an integer value 5. This helps us to keep track of how many chances are left.
  4. Then we print("Hey there! Guess a number b/w 1 to 20 which I am thinking of: ").
  5. Then create a for loop that loops 5 times.
  6. From within the for loop, ask the user to input() some number. Then take the input and convert it to an int type. Then store it in a variable called guess.
  7. Then the comparison starts. If guess < secret_number, then:
    • print("Guess is too low!")
  8. else if guess > secret_number:
    • print("Guess is too high!")
  9. else:
    • break the loop
  10. Then standing from outside of the if-else statements within the for loop, decrease 1 from chances_left.
  11. Then after converting chances_left to str() type, print() how many chances are left.
  12. Finally, get out of the for loop and then do the following:
    • check if guess == secret_number, then print("You guessed it right!")
    • else, print("You lose!") and also reveal the secret_number after converting it into str() type.

If you want to follow along with me, then let's begin the adventure!

What you will learn?

By doing this simple project, you will learn the following:

  • how to generate random integers
  • for loop in python
  • how to take input()
  • how to print() output
  • if, elif, else statements
  • ==, <, >
  • break keyword
  • how to convert variable of one type to another(type conversion) etc.

Things you will need

  • The very first thing you will need is the python itself. I am going to use python3. You can read this post to learn how to setup python3 on any operating system - https://realpython.com/installing-python/
  • After setting up python3, you will need a modern code editor like visual studio code. Yes, of course, you can do this simple project inside the default python IDLE or things like that, but the benefit of using a modern code editor like visual studio code is that it comes pre-baked with all the things you will ever need during your programming journey. It has a pre-built terminal, Integrated Git, debugging tools, extensions, and much much more. And more than anything else, it is completely free and open-source. 

You can download visual studio code from here according to your Operating system - https://code.visualstudio.com/download.

With these things set up, now you are good to go.

Getting Started

  • Create a folder named Guess the number anywhere on your computer.
  • Now just open visual studio code.
  •  Then inside visual studio code, click on File > Open Folder and choose the folder you created Guess the number.
  • Now click on this icon (like below) to create a new file and name it as guess.py:

new file creating steps

  • Now you will have something similar to this:

new file created

That's it now you are good to write the python code.

The Game

Let's import the random module first. We will use this module to generate a random integer. Type the following code:

# random module to generate random numbers
import random
  • The first line is a comment which describes what the code does. You don't have to type that though. But writing comments in your code is always a good habit that will help you to understand what this project is all about even if you look at this project maybe 5 or 6 years later 😇.

By the way, the random module already comes pre-baked with python. So you don't have to install them separately.

Now we have the needed module. So, let's define some global variables. The specialty of a global variable is that it can be accessed from anywhere in the program and you should define it at the very top.

Now type the following code below the above line:

# generate a random secret_number
secret_number = random.randint(1, 20)
# how many chances
chances_left = 5

print("Hey there! Guess a number b/w 1 to 20 which I am thinking of: ")
  • In the first line, we created a random integer using randint(lower_limit, upper_limit) function which is available from the random module. Then we stored that random number in a variable called secret_number.
  • Then we created a variable called chances_left and assigned it an integer value 5. This will help us to keep track of how many chances are left as I told earlier.
  • Then we print() a message saying "Hey there! Guess a number b/w 1 to 20 which I am thinking of: ".

Now we need to do the following steps repeatedly for 5 times:

  • Ask the user to enter a guess.
  • Then compare it with the number generated by the computer.
  • If the guess is low, then print a message for that.
  • If the guess is high, then print a message for that.
  • Then decrease 1 from how many chances_left before taking the next loop iteration.

But how we are going to do these things repeatedly? Here's where the concept of loops comes into play.

There are so many types of loops. The one we are going to use here is what's called a for loop.

The general syntax of for loop looks like this:

for loop general syntax

 Now type this. While you type the following code, make sure to indent lines as it is because indentation is everything in python:

# ask the player to guess 5 times
for i in range(1, 6):
  #converts input "string" to int
  guess = int(input("Take a guess: "))
  
  # checking
  if guess < secret_number:
    print("Guess is too low!")
  elif guess > secret_number:
    print("Guess is too high!")
  else:
    # user guessed it correctly, so jump out of the loop
    break

  # before taking next iteration
  # decrease 1 from chances_left
  chances_left = chances_left - 1
  print("Chances Left: " + str(chances_left))

# check if the guess matches the secret_number
if guess == secret_number:
  print("You guessed it right!")
else:
  print("You lose!")
  print("The number I thought was " + str(secret_number))

Now the explanation for the above code:

  • We are making a for loop that runs exactly 5 times. Inside that for loop, we put all the things we need to do repeatedly.
  • Now inside the for loop, first, we took the guess from the user using input("Take a guess: "). But the problem here is that whatever the user enters as input is considered/read by the computer as a string data type. But we need an integer. So we need to typecast or did the type conversion to convert str into an int. That's why we did this:

previously typed code which does type conversion from string to integer

  • Then comes the comparison part.  First, we checked if guess < secret_number, if so then:
    • print("Guess is too low!")
  • else check if guess > secret_number, if so then:
    • print("Guess is too high!")
  • Or else:
    • break out of the loop. And, by the way, this is how we write if else-if statement in python:

if elif else statement

  • After doing that, and before taking the next iteration, decrease 1 from chances_left and reveal how many chances are left. Here we also did type conversion, but it is from int to str to print it as a string:

type conversion from int to str. previously typed code

  • Finally, after getting out of the for loop, we did the following:
    • checked if guess == secret_number, if so then print("You guessed it right!")
    • Or else, print("You lose!") and also revealed the secret_number after converting it into str() type:

last line

That's it. Hooray, you have made the Guess the number/Number guessing game in python! 

It's time to run the game! To run this python program in the terminal, do the following:

  • From within visual studio code, click on the Terminal > New Terminal:

steps to open new terminal in visual studio code

  • Now a terminal will pop up at the bottom. In that terminal, enter the following code and hit the Enter key:
python3 guess.py
  • If you named your file something else, then instead of typing guess.py in the above code please type your file name.

This is my output which I got:

output which i got

Complete Code

Here is the final code for the "guess.py" file. If you got any errors, then make sure the code you typed up to this point inside the "guess.py" is exactly like the following including the indentations for the while loop because indentation is everything in python:

# random module to generate random numbers
import random

# generate a random secret_number
secret_number = random.randint(1, 20)
# how many chances
chances_left = 5

print("Hey there! Guess a number b/w 1 to 20 which I am thinking of: ")

# ask the player to guess 5 times
for i in range(1, 6):
  #converts input "string" to int
  guess = int(input("Take a guess: "))
  
  # checking
  if guess < secret_number:
    print("Guess is too low!")
  elif guess > secret_number:
    print("Guess is too high!")
  else:
    # user guessed it correctly, so jump out of the loop
    break

  # before taking next iteration
  # decrease 1 from chances_left
  chances_left = chances_left - 1
  print("Chances Left: " + str(chances_left))


# check if the guess matches the secret_number
if guess == secret_number:
  print("You guessed it right!")
else:
  print("You lose!")
  print("The number I thought was " + str(secret_number))

Wrapping Up

I hope you enjoyed this tutorial.

If you had any doubts, then please comment them below. Thank you ;)