← Back to Blog

while True + break — the classic pattern

The problem...

Sometimes you don't have a condition to start with. You just need the loop to run — and stop only when something specific happens inside.

A condition at the top doesn't always make sense. The decision to stop lives inside the loop, not outside it.

The idea!

while True creates a loop that runs forever. True is always true — so the condition never fails.

The only way out is break. You decide when. You decide why.

The syntax

while True:
    # runs forever
    if condition:
        break    # the only exit

Your first while True

while True:
    answer = input("Type 'quit' to exit: ")
    if answer == "quit":
        break

print("Goodbye.")

The loop asks forever. The moment the user types "quit"break fires — loop stops — program continues.

Why not just use a regular while?

# Regular while — condition at the top
answer = ""
while answer != "quit":
    answer = input("Type 'quit' to exit: ")

# while True — decision inside the loop
while True:
    answer = input("Type 'quit' to exit: ")
    if answer == "quit":
        break

Same result. But while True is cleaner when the exit condition is complex or when you need to do something before checking it.

A real example — input validation

while True:
    age = input("Enter your age: ")
    if age.isdigit():
        age = int(age)
        break
    print("Numbers only. Try again.")

Keep asking until the user gives a valid number. You can't know in advance how many tries that takes. while True handles it cleanly.

Multiple exit points

while True:
    command = input("Enter command: ")
    if command == "quit":
        print("Goodbye.")
        break
    if command == "exit":
        print("Exiting.")
        break
    print(f"Command '{command}' received.")

One loop. Multiple ways out. Each break is a different exit point.

Heads up!

  • while True runs forever — break is the only exit
  • Always make sure break can be reached — or the loop never stops
  • Every while True needs at least one break inside
  • Use it when the exit condition lives inside the loop, not outside

The mindset shift

Stop thinking: "I need a condition at the top."

Start thinking: "Sometimes the loop runs until something happens — and that something lives inside."

What you should understand now

  • while True creates an infinite loop
  • break is the only way out
  • Use it when you can't define the exit condition before the loop starts
  • Input validation is the classic use case — keep asking until the answer is valid
[ login to bookmark ] // copied! 21 views · 2 min
// resources
Code Example while_true_break.py
← prev More conditions, smarter loop next → Roll until you win
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.