Python Exercise 002 – Guess The Number Game With While Loop

In the Python Exercise 001, we made a Guess The Number game using for loop, in this exercise, we will make the same game using while loop. The difference between these two is quite easy to understand. With for loop, the user had a limited number of attempts to guess the number, in our example, it was 5. However, in while loop, the user will keep on guessing the number until they enter the correct one.

The first step is to import the random module.

import random

Greeting the user and asking for their name using the input() function.

print("Hello, please enter your name.")
player_name = input()

Generating a random number using random.randint() function and storing it in the secret_number variable.

secret_number = random.randint(1,100)

The next step is to ask the user to enter any number between 1 and 100, store it in the guess variable and convert it into an integer using the int() function.

print("Thanks, " + player_name + ". Please enter any number between 1 and 100. Enter your number: ")
guess = int(input())

With the help of while loop, we will check if the number entered by the user was greater than or less than the randomly generated number. Note that this block of code will only execute if the guess made by the user wasn’t correct. The while loop will not execute if the user guesses the number in the first attempt. If the number is greater than or less than the randomly generated number, we will ask the user to enter the number again and this block of code will keep on running until the user guesses the correct number.

while guess != secret_number:
    if guess < secret_number:
        print("Your guess is below the number, please guess again")
    else:
        print("Your guess is above the number, please guess again")
    guess = int(input())

If the user guesses the number correctly, the following block of code will execute.

if guess == secret_number:
    print(player_name + ", you guessed it!")

Source Code

import random

print("Hello, please enter your name.")
player_name = input()

secret_number = random.randint(1,100)

print("Thanks, " + player_name + ". Please enter any number between 1 and 100. Enter your number: ")
guess = int(input())

while guess != secret_number:
    if guess < secret_number:
        print("Your guess is below the number, please guess again")
    else:
        print("Your guess is above the number, please guess again")
    guess = int(input())
    
if guess == secret_number:
    print(player_name + ", you guessed it!")

Add comment