Control Flow

Break and Continue

break exits a loop early, while continue skips to the next iteration.

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
Grace
break exits the loop; continue skips to the next iteration. Both interrupt the natural fall-through.

break 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
save

Notes

See also

Run the complete example

Example code

Expected output

Ada
Grace
load
save

Execution time appears here after you run the example.