Control Flow
Break and Continue
break and continue control the nearest enclosing loop. They exist for loops whose body discovers an early stop rule or an item-level skip rule.
Use continue when the current item should not run the rest of the body. Use break when no later item should be processed.
The alternative is ordinary if/else nesting. Prefer break and continue when they keep the normal path flatter and easier to read.
continue skips the rest of the current iteration. The empty name is ignored, and the loop moves on to the next value.
Source
names = ["Ada", "", "Grace"]
for name in names:
if not name:
continue
print(name)Output
Ada
Gracebreak exits the loop immediately. The value after stop is never processed because the loop has already ended.
Source
commands = ["load", "save", "stop", "delete"]
for command in commands:
if command == "stop":
break
print(command)Output
load
saveNotes
continueskips to the next loop iteration.breakexits the nearest enclosing loop immediately.- Prefer plain
if/elsewhen the loop does not need early skip or early stop behavior.
See also
- related: For Loops
- related: While Loops
- contrast: Loop Else
Run the complete example
Expected output
Ada
Grace
load
save
Execution time appears here after you run the example.