Skip to main content

How to Repeat Code Until You Stop It in Python with while True and break

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Some loops don't know in advance how many times to run: a chat, a menu, a prompt that repeats until the user is done. while True runs the body over and over, and break leaves the loop the moment you decide. This guide loops until the user types quit, with real output from Python 3.15.2.

Syntax​

Syntax
while True:
<code>
if <condition>:
break
<more code>
PartWhat it means
while True:Runs the indented body again and again; True never stops it by itself
if <condition>: breakLeaves the loop immediately when the condition holds
After the loopThe code below the loop runs once break has run

Python's language reference: "The while statement is used for repeated execution as long as an expression is true". About break, it says: "It terminates the nearest enclosing loop".

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

repeat.py
while True:
answer = input("Type something, or quit to stop: ")
if answer == "quit":
break
print(f"You typed {answer}")

print("Bye")

The repeat.py script in a macOS-style code window: a while True loop reads an answer with input, breaks when it is quit, and otherwise prints it; Bye is printed after the loop.

The check comes right after reading the answer, so quit itself is never echoed.

Step 2: Run It​

Terminal
uv run python repeat.py

Type hello, press Enter, then type quit:

Output
Type something, or quit to stop: hello
You typed hello
Type something, or quit to stop: quit
Bye

The output in a terminal: the prompt, hello typed and echoed as You typed hello, the prompt again with quit typed, then Bye.

The loop ran twice. On the second turn break ended it, and Bye, the first line after the loop, ran.

Common Mistakes​

MistakeWhat happensDo this instead
Forgetting the breakThe loop never ends; stop it with Ctrl+CGive every while True a way out
Putting break outside a loopSyntaxError: 'break' outside loopUse break only inside for or while
Checking the condition after printingThe stop word is echoed tooCheck first, then act

Troubleshooting​

SymptomLikely causeFix
Typing quit doesn't stop itA trailing space or capital letters, such as Quit Compare answer.strip().lower()

FAQ​

Can I write while answer != "quit": instead?​

Yes, but then answer needs a value before the loop starts. while True with break reads the input in one place, at the top of the loop.

What does break do in nested loops?​

It leaves only the innermost loop it's in.

Conclusion​

while True kept asking until the answer was quit, break ended the loop on the second turn, and Bye printed after it.

Additional Resources​