-->

Python3.2.1.9 LAB: The break statement - Stuck in a loop

 3.2.1.9 LAB: The break statement - 

Stuck in a loop

The break statement - Stuck in a loop
The break statement - Stuck in a loop

If you're taking PCAP - Programming Essentials In Python , you may have encountered this question in 3.2.1.9 LAB: The break statement - Stuck in a loop.

Scenario

The break statement is used to exit/terminate a loop.

Design a program that uses a while loop and continuously asks the user to enter a word unless the user enters "chupacabra" as the secret exit word, in which case the message "You've successfully left the loop." should be printed to the screen, and the loop should terminate.

Don't print any of the words entered by the user. Use the concept of conditional execution and the break statement.

2 Solutions

First Solution (with break)

As the exercise asks, you need to include the keyword (break)

secret_word = ""
while True:
    secret_word = input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop: ")
    if secret_word == "chupacabra":
        print("You've successfully left the loop.")
        break

Second Solution (without break, but with else)

secret_word = "chupacabra"
word = input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop: ")

while word != secret_word:
    word = input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop: ")
else:
    print("You've successfully left the loop.")


 =================================================================================

Follow the blog to be the first to know ❤

Post a Comment

0 Comments