Lesson explanation
After this lesson, you will be able to:
while when repetition depends on changing state.break when the target is found.continue.Use while when the program should repeat as long as a condition remains true:
while attempts < max_attempts:
...Unlike a for loop, a while loop does not update its controlling state automatically. Your code must change the value used by the condition, or the loop may run forever.
break exits the entire loop immediately. Use it when continuing would be unnecessary, such as after finding a healthy server.
continue skips the remaining statements in the current iteration and returns to the loop condition. Before continuing, make sure any required index or counter update has already happened; otherwise the loop can repeat the same item forever.
Use for for a known numeric range or direct iteration over values. Use while when the stopping point depends on state that changes during execution.
💡 Tip: Before running a
whileloop, identify the condition, the state update, and the event that ends the loop.
The counter update eventually makes the condition false.
attempt = 1
while attempt <= 3:
print(f"Attempt {attempt}")
attempt += 1Output:
Attempt 1
Attempt 2
Attempt 3Without attempt += 1, this loop would not finish.
break exits as soon as the healthy status is found.
statuses = ["error", "error", "ready"]
index = 0
while index < len(statuses):
status = statuses[index]
index += 1
if
Output:
Ready on check 3No later iteration is needed after success.
continue skips the print for the invalid value but keeps the loop running.
readings = [18, -1, 22]
index = 0
while index < len(readings):
reading = readings[index]
index += 1
if
Output:
18
22The index is updated before continue, so the loop moves forward.
continue and breakOne condition skips unusable input; another ends processing.
commands = ["", "status", "stop", "deploy"]
index = 0
while index < len(commands):
command = commands[index]
index += 1
Output:
statusThe empty command is skipped, and processing ends at stop.
| Need | Tool |
|---|
break when only one item should be skipped.continue before a required index update.while for a simple fixed range when for is clearer.Python for Developers
Assembled code
Generated code is hidden by default. Expand it only if you want to inspect what your current blank values produce.
0 / 6 tasks completed
| Repeat while state remains valid | while |
| Exit the loop completely | break |
| Skip only this iteration | continue |
| Avoid an infinite loop | Update the controlling state |