Home » Programming » Number Guessing Game in Python

# Number Guessing Game in Python In this post, we are going to bring everything we have learned so far together to create a simple Number Guessing Game in Python.

This will involve creating a new Python program, handling user input, using the `if `statement as well as using looping constructs.

We will also, use an additional library or module, that is not by default available to our program; this will be the random number generator module.

To make sure everything is working correctly we will add a simple print() statement to the file so that we can test out running it.

We can add anything we like, including printing out ‘Hello World’. However the example shown below shows a welcome message as ‘Welcome to the Number Guessing Game in Python‘.

`print ('Welcome to the Number Guessing Game in Python')`

## What will the program do?

The aim of our number guessing game in Python is to guess the number that the program has come up with.

Essentially, the program logic is

• The program randomly selects a number between 1 and 10.
• It will then ask the player to enter their guess.
• It will then check to see if that number is the same as the one the computer randomly generated; if it is then the player has won.
• If the player’s guess is not the same, then it will check to see if the number is higher or lower than the guess and tell the player.
• The player will have 4 chance to guess the number correctly; if they don’t guess the number within this number of attempts, then they will be informed that they have lost the game and will be told what the actual number was.

Also Read : Iteration/Looping available in Python

## Creating the Game

### Generate the Random Number

We will start off by looking at how we can generate a random number. Up to this point we have only used the built-in functions that are provided by Python automatically. In actual fact, Python comes with very many modules provided by the Python organization itself, by third party vendors and by the open source (typically free) software community.

The` random` module provides implementations of pseudo-random number generators for use in application programs. These random number generators are referred to as pseudo because it is very hard for a computer to truly generate a series of random numbers. Instead it does its best to mimic this using an algorithm. Which by its very nature will be based on some logic which will mean that it is not impossible to predict the next number. Hence it is not truly random. For our purposes this is fine but there are applications, such as security and encryption, where this can be a real problem.

To access the `random` module in Python we need to import it. This makes the module visible in the rest of the Python file (in our case to our program). This is done using

```import random
number_to_guess = random.randint (1, 10)```

Once we have imported it, we can use the functions within this module, such as `randint`. This function returns a random integer between the first and second arguments. In the above example, it means that the random number generated will be between 1 and 10.

The variable `number_to_guess` will now hold an integer which the player of the game must guess to win.

### Obtain an Input from the User

We now need to obtain from the user representing their guess. We can use `input()` function which returns a string and then the integer function that will convert that string into an integer. Therefore we can write:

``guess = int (input ('Please guess a number between 1 and 10: '))``

This will store the number they guessed into the variable `guess`.

### Check to see if the Player has Guessed the Number

We now need to check whether the player has guessed the correct number. We could use an` if` statement for this, however we are going to repeat this test until either they have guessed correctly or until they have run out of attempts.

Therefore we will use a `while` loop and check to see if their guess equals the number to be guessed.

``````guess = int (input ('Please guess a number between 1 and 10: '))
while number_to_guess != guess:``````

The above loop will be repeated if the number they entered did not match the number to be guessed. Therefore, we can print a message telling the player that their guess was wrong.

``````guess = int (input ('Please guess a number between 1 and 10: '))
while number_to_guess != guess:
print ('Sorry wrong number')``````

Now we need the player to make another guess otherwise the program will never terminate, so we can again prompt them to enter a number.

``````guess = int (input ('Please guess a number between 1 and 10: '))
while number_to_guess != guess:
print ('Sorry wrong number')
guess = int(input ('Please guess again: '))``````

### Check They haven’t Exceeded Their Maximum Number of Guess

We also said above that the player can’t play forever; they have to guess the correct number within 4 attempts. Therefore, we need to add some logic which will stop the game once they exceed this number.

Therefore, we will need a variable to keep track of the number of attempts they have made. We should call this variable something meaningful so that we know what it represents. For example, we could call it` count_number_of_tries` and intialize it with the value 1.

``count_number_of_tries = 1``

This needs to happen before we enter the while loop. Inside the while loop we need to do two things

• check to see if the number of tries has been exceeded,
• increment the number of tries if they are still allowed to play the game.

We will use an if statement to check if the number of tries has been met. If it has we want to terminate the loop; the easiest way to this is via a` break` statement.

``````if count_number_of_tries == 4:
break``````

If we don’t break out of loop we can increment the count using the ‘+=’ operator. Thus, we now have

```count_number_of_tries = 1
guess = int (input ('Please guess a number between 1 and 10: '))
while number_to_guess != guess:
print ('Sorry wrong number')
if count_number_of_tries == 4:
break
guess = int(input ('Please guess again: '))
count_number_of_tries += 1```

### Notify the Player Whether Higher or Lower

We also said at the beginning that to make it easier for the player to guess the number. We should indicate whether their guess was higher or lower than the actual number. To do this we can again use the `if` statement; if the guess is lower we print one message and same for higher.

At this point we have a choice of regarding whether to have a separate if statement to that used to decide if the maximum attempt has been reached. Each approach can work but the latter indicates that these conditions are all related so that is the one we will use.

The `while` loop now looks like

```count_number_of_tries = 1
guess = int (input ('Please guess a number between 1 and 10: '))
while number_to_guess != guess:
print ('Sorry wrong number')
if count_number_of_tries == 4:
break
elif guess < number_to_guess:
print ('Your guess was lower than the number')
else:
print ('Your guess was higher than the number')
guess = int(input ('Please guess again: '))
count_number_of_tries += 1```

Notice that the `if` statement has a final else which indicates that the guess was higher. This is fine as by this point it is the only option left.

### End of Game Status

Now we have covered all the situations that can occur while the game is being played. All that is left for us to do is to handle the end of game messages.

If the player has guessed the number correctly, we want to congratulate them. If they did not guess the number, we want to let them know what the actual number was. We will do this using another if statement which checks to see if the player guessed the number or not. After this we will print an end of game message.

``````if number_to_guess == guess:
print ('Well done you won!)
print ('You took', count_number_of_tries, 'attempts to complete the game')
else:
print ('Sorry - you loose')
print ('The number you needed to guess was', number_to_guess)
print ('Game Over')``````

## The Complete Listing

```import random
print ('Welcome to the Number Guessing Game in Python')

# Initialize the number to be guessed
number_to_guess = random.randint (1, 10)

# Initialize the number of tries the player has made
count_number_of_tries = 1

# Obtain their initial guess
guess = int (input ('Please guess a number between 1 and 10: '))
while number_to_guess != guess:
print ('Sorry wrong number')

# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 4:
break
elif guess < number_to_guess:
print ('Your guess was lower than the number')
else:
print ('Your guess was higher than the number')

# Obtain their next guess and increment number of attempts
guess = int(input ('Please guess again: '))
count_number_of_tries += 1

# Check to see if they did guess the correct number
if number_to_guess == guess:
print ('Well done you won!)
print ('You took', count_number_of_tries, 'attempts to complete the game')
else:
print ('Sorry - you loose')
print ('The number you needed to guess was', number_to_guess)
print ('Game Over')```

And a sample run of the program us shown below.

``````Welcome to the Number Guessing Game in Python
Please guess a number between 1 and 10 : 7
Sorry wrong number
Your guess was higher than the number