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 secret_number: print["Your guess is above the number, please guess again"] else: break
Once the execution in for loop starts either because it has looped five times or the user was able to guess the number correctly, the next step is to print the results. This block of code will execute if the user guessed the number correctly.
if guess == secret_number: total_guesses = str[total_guesses + 1] print[player_name + ", it took you " + total_guesses + " attempts to guess the number"]
And if the user runs out of their guesses [5], this block of code will execute.
if guess != secret_number: secret_number = str[secret_number] print["Nope, the number I was thinking was " + secret_number + "."]
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. Remember, you have only 5 attempts"] for total_guesses in range[5]: guess = int[input[]] if guess < secret_number: print["Your guess is below the number, please guess again"] elif guess > secret_number: print["Your guess is above the number, please guess again"] else: break if guess == secret_number: total_guesses = str[total_guesses + 1] print[player_name + ", it took you " + total_guesses + " attempts to guess the number"] if guess != secret_number: secret_number = str[secret_number] print["Nope, the number I was thinking was " + secret_number + "."]
Posted from Data Science With Python SteemPress : //datasciencewithpython.info/python-exercise-001-make-a-guess-the-number-game/