Meaning
Runs an infinite loop that exits when a given condition becomes true; used for polling, waiting, or repeating an action until an external state changes.
Primary Function
Loop control
Communicative Purpose
Repeatedly execute code until a break condition is met, allowing the loop to run indefinitely until manually stopped.
Pattern
while True: if ; break
Core Structure
while True: if ; break
Função primária
Loop control
Propósito comunicativo
Repeatedly execute code until a break condition is met, allowing the loop to run indefinitely until manually stopped.
Situações de gatilho
Waiting for user input, polling a sensor or file, retrying an operation until success, implementing a game or event loop.
Contextos
General-purpose Python scripts, embedded systems, game development, server loops, automation tools.
Padrão
while True: if ; break
Estrutura central
while True: if ; break
Slots de substituição
break_condition: boolean expression that determines when to exit the loop
Colocados típicos
- time.sleep()
- input()
- threading.Event
- flags
- retry counters
Substituições comuns
- using a flag variable (while not done: ...)
- using a for loop with else
- using try/except to break
- using itertools.count with break
Erros comuns
forgetting to update the break condition leading to an infinite loop, incorrect indentation causing SyntaxError, placing break outside the loop
Similar / contraste
while not condition: ... (loop runs while condition is false); for loop with else clause; recursion with base case; do‑while emulation via while True: if not condition: break
Interferências
Coming from languages with do‑while loops: may expect the loop body to execute at least once → here the loop may execute zero times if the break condition is initially true.
Família do chunk
- infinite loop
- polling loop
- retry loop
- event loop
Nuance
When NOT to use: when a guaranteed first execution is required (use a do‑while style loop). Performance/resource implications: tight loops can consume CPU; consider adding a sleep or yield to avoid busy‑waiting. Non‑obvious boundary conditions: if the break condition never becomes true the loop will run forever; consider adding a timeout or maximum iteration count to prevent hanging.
Efeito pragmático
Makes the intent of an infinite loop with an explicit exit point clear, reducing reliance on mutable flag variables and improving readability.
Dica de memória
Think of a 'busy wait' loop that runs forever until you hit the break button.
Nota
Always ensure the break condition can become true; consider adding a timeout or maximum iteration count to prevent accidental infinite loops.
Upgrade path
Replace with a flag‑controlled loop: while not done: ... ; done = True
Log in to save chunks.