Python for AIPython for AI
Control Flow

Break, continue, and pass

Control exactly how your loops run

Loops normally run from start to finish. Sometimes you need more control: stop early, skip one item, or leave a block empty for now. Python has three small keywords for this.

FeatureWhat it doesLoop keeps going?
breakExits the loop immediatelyNo
continueSkips to the next roundYes
passDoes nothing (placeholder)Yes
What each keyword does inside a loop.

break: stop the loop

break ends the loop right away, even if there are items left or the condition is still true. The program continues after the loop.

python
numbers = [4, 8, 15, 16, 23, 42]

for n in numbers:
    if n > 15:
        print("Found a number above 15:", n)
        break
    print("Checked", n)

The chatbot pattern

A very common use of break: a chatbot loop runs forever with while True and only stops when the user asks it to.

python
while True:
    user_text = input("You: ")

    if user_text.lower() == "quit":
        print("Goodbye!")
        break

    print(f"Bot: You said '{user_text}'")
while True with a break inside is a very common pattern. Make sure there is always a way to reach the break, or the loop will never end.

continue: skip this round

continue skips the rest of the current round and jumps straight to the next one.

python
for n in range(1, 8):
    if n % 2 == 0:
        continue      # skip even numbers
    print(n)
# prints 1, 3, 5, 7

In a chatbot, use it to ignore empty messages instead of sending them to the AI:

python
while True:
    user_text = input("You: ").strip()

    if user_text == "":
        continue      # ask again

    if user_text == "quit":
        break

    print("Sending to AI:", user_text)

pass: do nothing

Python requires at least one line inside every block. pass is a placeholder that does nothing. Use it while you sketch out code you'll fill in later.

python
def summarize_document(text):
    pass   # TODO: write this later

for item in []:
    pass

if True:
    pass
pass doesn't change how a loop runs. That's the difference from continue: code after pass still runs.

Common mistakes

  • Using break outside a loop. It only works inside for and while.
  • In a while loop, putting continue before the line that updates the counter. That creates an infinite loop.
  • Confusing pass with continue. pass does not skip anything.

What's next?

With loops under control, it's time to package code into reusable functions.