while, break, and continue
Scenario: Retry until a service responds, but stop after a safe limit.
New words, in plain English
- while loop - a loop that repeats while its condition is true
- break - leave the nearest loop now
- continue - skip to the next iteration
Use while when repetition depends on changing state. Ensure the condition can become false. break exits; continue skips remaining work; a loop else runs only when no break occurred.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
attempt = 0
while attempt < 3:
attempt += 1
if attempt == 2:
continue
if attempt == 3:
break
Tip: A bounded retry loop needs both a changing counter and a maximum.
Goal: Practice this idea in the py-conditionals-loops challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.