🐍 Loop Control

loop

Good to know

⭐️ break and continue work only inside loops (for or while). Pass can be used anywhere (loops, if-statements, functions) as a β€œdo nothing” placeholder. Python does not allow break or continue directly inside an if unless that if is inside a loop.


break – stop the loop completely

Stops the entire loop immediately.

for char in "123-456-7890":
    if char == "-":
        break
    print(char, end="")
 
# Output: 123

continue – skip to the next iteration

Skips the rest of the loop body and continues with the next value.

for char in "123-456-7890":
    if char == "-":
        continue  # skip dashes
    print(char, end="")
 
# Output: 1234567890

pass – do nothing (placeholder)

Useful when a block is required syntactically, but you aren’t ready to write code yet.

for char in "ABC":
    if char == "B":
        pass  # do nothing
    print(char)

Also works inside if/else:

if True:
    pass  # placeholder for future logic

break and continue in while loops

i = 0
while i < 10:
    if i == 5:
        break
    if i % 2 == 0:
        i += 1
        continue
    print(i)
    i += 1