Search⌘ K
AI Features

Solution: Break the Loop

Explore how to control infinite loops in Python by using break to exit loops and continue to skip iterations. Learn to manage user input effectively with conditional statements to keep interactions dynamic and responsive.

We'll cover the following...

This program keeps a conversation going until the user says "bye". It also ignores empty input.

  • while True: creates an infinite loop, meaning it keeps running until you tell it to stop.

  • input() lets the user type something, which is stored in the variable word.

  • if word == "bye": checks if the user typed "bye".

    • If yes, the break statement stops the loop.

  • if word == "": checks if the user just pressed Enter without typing anything.

    • If yes, continue skips the rest of the loop and starts over.

  • Otherwise, Python prints whatever the user said.

while True:
    word = input("Say something: ")
    if word == "bye":
        break
    if word == "":
        continue
    print("You said:", word)
Asking for words, skipping blanks, and stopping at “bye”