🎓 A1Learner
🔍

Python For Break & Continue

break and continue are statements that control a for loop from inside.

Break inside a for loop

The walk stops at Bob. Later names are not printed.

names = ["Ada", "Bob", "Cy", "Dee"]
for name in names:
    if name == "Bob":
        break
    print(name)
print("Done")

Continue inside a for loop

Bob is skipped. The walk still visits Cy.

names = ["Ada", "Bob", "Cy"]
for name in names:
    if name == "Bob":
        continue
    print(name)

Pass inside a loop

The pass line does nothing yet. It holds the place for later code.

for number in range(3):
    pass
print("Loop finished")

Else when nothing is found

No name matches, so no break happens. The else block runs.

names = ["Ada", "Bob"]
for name in names:
    if name == "Cy":
        print("found")
        break
else:
    print("not there")

Example

names = ["Ada", "Bob", "Cy", "Dee"]
for name in names:
    if name == "Cy":
        print("found")
        break
else:
    print("not there")

Key points

  • Use break inside a for loop to stop the walk early.
  • Use continue inside a for loop to skip one item.
  • Use pass inside a loop as an empty placeholder.
  • The Conditionals section introduced pass.
  • The else block on a for loop runs when the loop finishes without break.
  • Search pattern: loop, test each item, break when you find it, and use else for not found.

In this example, names holds four names. The loop checks Ada first, and it is not Cy. It checks Bob next, and it is not Cy. It then checks Cy and finds a match. It prints "found" and break leaves the loop. The else block does not run, because break ended the loop.

Note

Loop else means finished without break.

It does not mean the opposite of an if else.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

In a for-else search, when does the else block run?