Title: Write a higher/lower game that demonstrates a while loop's else block in Python
This post shows how to build a simple higher/lower game. Perhaps more importantly, it demonstrates the while loop's else block.
A while loop ends "normally" when its test condition becomes False. If the loop ends in any other way, for example because of a break or return statement, the loop ends early. If the loop has an else block, the statements inside that block execute only if the loop ends normally.
The following code shows a simple higher/lower game that demonstrates a while loop's else block.
import random
print('\nGuess a number between 1 and 100\n')
target = random.randint(1, 100)
# Get the first guess.
guess = input('Guess: ')
num_guesses = 1
while guess != target:
if guess == 'q': # The user wants to quit.
print('Bye!')
break
guess = int(guess)
if target < guess:
guess = input('Lower: ')
num_guesses += 1
elif target > guess:
guess = input('Higher: ')
num_guesses += 1
else:
print(f'You guessed it in {num_guesses} guesses!')
The progam first imports random and generates a random target number between 1 and 100. It then prompts the user and gets the user's first guess.
Next, the program enters a while loop that executes until the user guesses the target number. The program has just prompted the user and gotten a guess, so the code inside the loop processes that guess.
If the guess is "q," the user is trying to quit the game. In that case, the code says "Bye!" and breaks out of the loop. (In a more robust game, you might also check for Q and you should probably dal with the user entering a non-numeric value like "ten" or "banana.")
If the user did not enter "q," the program converts the guess into a number. It compares the numeric guess to the target number and displays an appropriate "Higher:" or "Lower:" prompt to get the user's next guess.
If the user guessed the correct target number, the code does not display a new prompt, the loop's condition guess != target is False, so the loop ends "normally."
The loop's else block displays a message telling the user how many guesses they took. Because this statement is in the else block, it does not execute if the loop ended because of a break statement. That means the user sees either the "Bye!" message or the success message but not both.
Conclusion
A while loop's else block lets you easily take different actions depending on whether the loop ends normally or via some shortcut like a break statement.
Are there other ways to handle this? Sure. In this example, you could check whether the user's final guess matches the target number. In a more confusing loop, you could control the loop with a Boolean variable and then check to see if it is False after the loop ends. Those techniques work, but they can be more confusing in some programs. The else block is clean and intuitive, at least if you know it exists!
Download the example to experiment with it and to see additional details.
|