Guess the Random Number using Python

thumbnail

Today, we will be creating a simple program to guess the random number using Python. Before we start, you need to import random to create a random number. The code is show below.

We will use input() to enter the number ant int() to return the number into integer. The we use while with value True to repeat again and again. If you enter the guess value less the random value then the program will print text “Your guess is not correct, the number is higher”, if you enter the guess value more than the random value, then the text will print “Your guess is not correct, the number is lower”. But, if your guess is correct then the output text will be “Congratz, you guess it!”.

# Created by inpows
# Visit inpows.com for more python tutorials

import random

n = random.randint(1,10)

guess = int(input("Enter an number from 1 to 9: "))

while True:
    if guess < n:
        print("Your guess is not correct, the number is higher")
        guess = int(input("Enter an number from 1 to 9: "))
    elif guess > n:
        print("Your guess is not correct, the number is lower")
        guess = int(input("Enter an number from 1 to 9: "))
    else:
        print("Congratz, you guess it!")
        break

The output will be:

Enter an number from 1 to 9: 1
Your guess is not correct, the number is higher
Enter an number from 1 to 9: 7
Your guess is not correct, the number is lower
Enter an number from 1 to 9: 5
Your guess is not correct, the number is lower
Enter an number from 1 to 9: 4
Your guess is not correct, the number is lower
Enter an number from 1 to 9: 3
Your guess is not correct, the number is lower
Enter an number from 1 to 9: 2
Congratz, you guess it!

Read another python tutorial.

Back To Top