Number Guessing Game in Python

This python program illustrates how to implement simple number guessing game.

We first generate random number using import random python module and then we read number from user. If generated number is equal to given number then user WON the game otherwise user need to RE-ENTER another number until user guess the number correctly.

In this program while True: is used to loop infinitely and when user guess the number correctly then we come out from loop using break statement.

Program


import random
while True:
    number = int(input('Enter number form 1 to 10: '))
    generated = random.randint(1,10)
    if generated == number:
        print('You Won!')
        break
    else:
        print('Try Again')

Output

Enter number form 1 to 10: 2
Try Again
Enter number form 1 to 10: 4
Try Again
Enter number form 1 to 10: 2
Try Again
Enter number form 1 to 10: 3
Try Again
Enter number form 1 to 10: 6
You Won!