Coders Packet

Random number guessing game using Python

By Shubham Suresh Chavan

This is a simple Python program that generate a random number and you have to guess that random number correctly. The Final result will show your number of attempts

Step 1:- import Python Random module.

Firstly you have to install the Python random module using the command:

This random module can generate random numbers in Python. To use this module you have to import it into your program.

you can import it using a single line of code.

import random


Then, you have to set flag = True for a while condition.


flag = True


Step 2:- Take Upperbound from the user.

In while, we will take a number input from the user to set an upper bound for the game. Even we have to make sure that the input we take from the user is only a numeric value. we will check it using the isdigit() function.

while flag:
        print("'Welcome to guess game'")
        num = input(" Type a number for an upper bound:- ")

        if num.isdigit():
            print("Lets Play!")
            num = int(num)
            flag = False
            print("invalid input! plases enter number")


Step 3:- Use the Random function to generate a random number.

We will use the random function by passing two parameters 1. starting point, 2. ending point

secret = random.randint(1,num)

Step 4:- Take a guessing input from the user.

We need to initialize two variable:

1. guess:- "to take input from the user",

2. count:- "to count the number of attempts".

Then, we will check the input given by the user is in numeric format or not. for that, we will use the isdigit() function again.

guess = None
count = 1

while guess != secret:
    guess = input('please type a number between 1 and'+str(num)+"  :-")
    if guess.isdigit():
        guess = int(guess)

Step 5:- Checking correct guess and Number of  Attempts.

Finally, we will write a code to check the guess number is correct or not? and how many attempts we need to guess the correct number.


    if guess==secret:
        print("you got it!")
         print('please try again!')
print('you took = ',count,'guess')






Download Complete Code


No comments yet