Trusted answers to developer questions

How to create a guessing game using while loop in Python

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Overview

The while loop in python is used to execute a code block multiple times. They are often used in building interactive programs and games.

In this shot, we want to create a guessing game that will return a congratulatory message to a user after making a correct guess. We will use the while loop in writing this code.

Code

Let’s try the below-given code by providing the input in the, Enter the input below, block:

correct_guess=9
guess_count=0
guess_limit=3
while guess_count<guess_limit:
guess = int(input('Guess a number: '))
guess_count += 1
if guess == correct_guess:
print('Congratulations! You won!')
break
else:
print('sorry you lost')

Enter the input below

Output

The output on successful guess will be:

Guess a number: 9
Congratulations! You won!

Explanation

Here’s the explanation of the above-given code:

  • Lines 1-3: We are creating integer variables

  • Line 4: Using the while loop, we stated a condition that the variable guess_count should be less than the variable guess_limit. In other words, the number of guesses the user has to make should not exceed 3.

  • Line 5: We request the user input the correct guess and convert it to an integer value simultaneously.

  • Line 6: We increment the variable guess_count by 1.

  • Line 7: We are using the if statement within the loop stating that if the user made a guess, that is equal to the value of the correct_guess.

  • Line 8: We are displaying/printing the congratulatory message if the condition at line 7 is true.

  • Line 9: We use the break statement to terminate the loop.

  • Line 10: We are using the else statement to return another output if the conditions provided in the previous codes are not met, or they are false.

  • Line 11: We are displaying/printing the sorry message.

RELATED TAGS

python
loop
while
game

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
Did you find this helpful?