Creating a 'guess the number' game in Python

Let's dig right in!

For starters let's import random that's a standard python library. You don't need to pip install it.

import random

From random we will use randint which allows us to return a random integer value between two lower and higher limits (including both limits) provided as two parameters. NB: This method is only capable of generating integer-type random values.

So let's setup our function and name it guess() which will take the maximum value x. So we will input this value whenever we call the function.

def guess(x):

Next let's create a variable that will hold the random number generated; We will call the variable random_number and set guess to 0 (No input made by user)

random_number = random.randint(1, x)
guess = 0

The fourth step is to create a while loop (repeat the action of asking the user for an input and check if the number inputed is too low or high). With the while loop running we would input some conditions using if ... else statements to check if the users entry is too high or low(As a guide for the user to amend input).

    while guess != random_number:
        guess = int(input(f'Guess a number between 1 and {x}: '))
        if guess < random_number:
            print('Too low')
        elif guess > random_number:
            print('Too high')

If the user guesses the right answer we want the program to exit the while loop and print 'They got the number right!'. How do we do that? With a simple print function to be executed outside the while loop. As simple as that!

So our entire program should look like below, when we request the user to guess a number between 1 and 10;

import random


def guess(x):
    random_number = random.randint(1, x)
    guess = 0
    while guess != random_number:
        guess = int(input(f'Guess a number between 1 and {x}: '))
        if guess < random_number:
            print('Too low')
        elif guess > random_number:
            print('Too high')

    print("That's right!")


guess(10)

That simple!

If you need assistance with your projects feel free to email me at info@airgad.com or whatsapp Jesse stay safe!