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.
| Feature | What it does | Loop keeps going? |
|---|---|---|
| break | Exits the loop immediately | No |
| continue | Skips to the next round | Yes |
| pass | Does nothing (placeholder) | Yes |
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.
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.
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.
for n in range(1, 8):
if n % 2 == 0:
continue # skip even numbers
print(n)
# prints 1, 3, 5, 7In a chatbot, use it to ignore empty messages instead of sending them to the AI:
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.
def summarize_document(text):
pass # TODO: write this later
for item in []:
pass
if True:
passpass doesn't change how a loop runs. That's the difference from continue: code after pass still runs.Common mistakes
- Using
breakoutside a loop. It only works insideforandwhile. - In a
whileloop, puttingcontinuebefore the line that updates the counter. That creates an infinite loop. - Confusing
passwithcontinue.passdoes not skip anything.
What's next?
With loops under control, it's time to package code into reusable functions.