DEV Community

Cover image for python guessing game
Introschool
Introschool

Posted on • Updated on

python guessing game

Subscribe to our Youtube Channel To Learn Free Python Course and More

Guessing Game
Here comes the interesting part of the learning. Learn things by building stuff is the best way of learning. In this section, we are going to make a simple game in which computer will randomly select the number from 1-50 and we will ask the user to guess the number. If he selects the number in 5 guesses then he will win the game otherwise he will lose.

To randomly selects the number we will use Python’s built-in Random module. Let’s see what is random module and how you can use it.

Random Module
To make the Guessing Game, we will use Python’s built-in random module. The random module is used to generate random numbers. The random module has so many built-in functions that are used to generate random numbers. Let’s see some of the random module functions.

First of all, we have to import the module to use it.

import randomimport random
Enter fullscreen mode Exit fullscreen mode

randint
random.randint(a, b)

The randint function of the random module takes two integers as an argument and generates one random number in the range [a, b] including both the numbers.

random.randint(2,9)
# Output: 7
Enter fullscreen mode Exit fullscreen mode

random
random.random()

This function is used to generate a floating point number between 0 and 1.
random.random()

random.random()
# Output: 0.8795690805656851
Enter fullscreen mode Exit fullscreen mode

Choice
random.choice(seq)

This function selects one random element from a sequence. If the sequence is empty, Interpreter raises IndexError.

random.choice([1, 4, 5, 8, 11])
# Output: 4

random.choice(('a', 'b', 'c'))
# Output: 'c'
Enter fullscreen mode Exit fullscreen mode

randrange
random.randrange(begin, end, step)

This function is used to generate a randomly selected element from range(start, stop, step).

random.randrange(5, 20)
# Output: 11

random.randrange(13, 33, 2)
# Output: 17
Enter fullscreen mode Exit fullscreen mode

You can see the random module documentation for more functions and other details.

Let’s Start the Game
What’s the Game?
*The computer will randomly select a number from 1 to 50.
*A user will have 5 chance to guess the number.
*To make the game interesting we can help the user to guess
the correct number.
*If he guesses a number greater than the actual number then
we will tell him “Your guess is too high”.
*If he guesses a number smaller than the actual number then
we will tell him “Your guess is too low”.
*If he guesses the correct number in the given 5 chance then
It’s a win.
*Otherwise, It’s a lose.

How to make it?
To make this game, we will simply create a file name game.py and we will write our entire code in this file. But before start writing the program, we will write pseudo code. The pseudo code is a way to structure your thinking process. We will break the problem into smaller parts and then we will try to solve it.

Guessing Game Pseudo Code

1.Start the game.
2.Print the ‘How to play guide”
3.Generate the random number from 1 to 50.
4.Take the user input.
5.Compare user input with the number that computer selected.
6.If it’s equal then print ‘You win the game’.
7.If it’s lesser then print ‘Your guess is too low’.
8If it’s greater then print ‘Your guess is too high’.
9.Repeat from step 4 to step 8 four more times to give him 5
chance.
10.At last, if he is unable to guess then print ‘Sorry, you
lost the game’.

*To make this game we will write the function and all the
logic of the game inside the function. So every time you
call the function the game will start. You can also do it
without making the function but by making a function, it
will make your code clean and clear. Functions also describe
as a group of statements and expression that perform a
specific task.

# game.py

def guess_game():
    pass

# Here we use pass statement, so the interpreter will run the function without error.

Enter fullscreen mode Exit fullscreen mode

Now let’s write the how to play guide. To write it we will use the print function.

import random


# Number selected by the computer.
random_num = random.randint(1,50)
Enter fullscreen mode Exit fullscreen mode

Taking input from the user.

guess_num = input('Guess the number: ')
Enter fullscreen mode Exit fullscreen mode

Now we have to give the user 5 chance, and there will be some repetitive steps. To implement this we can use for loop.

for chance in range(5, 0, -1):
    if chance:
        print(f'You have {chance} chance to guess the number.')
        guess_num = input('Guess the number: ')
        if int(num) == random_num:
            print('Hurray!, You guess the correct Number')
            break
        elif int(guess_num) > random_num:
            print('Your guess is too high.')
        elif int(guess_num) < random_num:
            print('Your guess is too low.')
else:
    print(f'Sorry, you lost the game.\n The correct number was          {random_num}')
Enter fullscreen mode Exit fullscreen mode

*First, we started a for loop using range function. You know
that range function takes three parameters: start, stop and
step. We give the start parameter 5, end 0 and step -1
because we want to print the number of chances left every
time the user guesses the number.
*Next, we write a for...else condition. The else block just
after for is executed only when the loop is NOT terminated
by a break statement. Inside for loop, in if condition, we
are taking the truthy values of variable chance.
*In nested if condition we are comparing the number guess by
the user and random number generated by the random.randint()
function. According to the result, we are printing the
statements. We know that the type of the output of input
function is always the string that’s why we are using int()
function to convert it into the integer.
*Once the user guesses the correct number, we don’t want our
loop to continue, that’s why we used break statement in case
of both numbers are equal.
*The moment it becomes zero the program will not enter into
the if condition. It will directly go to the else condition
and print the statement.

See the entire code below.

# game.py

import random

# Function definition
def guess_game():
    print("Welcome to the Guessing Game.\nThe computer has selected one random number from 1 t0 50.\nGuess the number.\nLet's Start")
    random_num = random.randint(1, 50)
    for chance in range(5, 0, -1):
        if chance:
            print(f'You have {chance} chance to guess the number.')
            guess_num = input('Guess the number: ')
            if int(guess_num) == random_num:
                print('Hurray!, You guess the correct Number')
                break
            elif int(guess_num) > random_num:
                print('Your guess is too high.')
            elif int(guess_num) < random_num:
                print('Your guess is too low.')
    else:
        print(f'Sorry, you lost the game.\n The correct number was {random_num}')


guess_game()   # calling the funciton

# Output: 
'''
Welcome to the Guessing Game.
The computer has selected one random number from 1 t0 50.
Guess the number.
Let's Start
You have 5 chance to guess the number.
Guess the number: 25
Your guess is too high.
You have 4 chance to guess the number.
Guess the number: 13
Your guess is too high.
You have 3 chance to guess the number.
Guess the number: 6
Your guess is too high.
You have 2 chance to guess the number.
Guess the number: 3
Your guess is too high.
You have 1 chance to guess the number.
Guess the number: 2
Hurray!, You guess the correct Number
'''

Enter fullscreen mode Exit fullscreen mode

Top comments (0)