Controlling loops#
Normally a loop runs all its iterations. Sometimes you need more control:
| Statement | What it does |
|---|---|
break |
Exit the loop immediately |
continue |
Skip the rest of this iteration, go to the next one |
pass |
Do nothing (placeholder) |
break - exit the loop early#
Use break when you've found what you're looking for, or when there's no reason to continue.
break with while True#
The most common use: an endless loop that exits when the user wants.
continue - skip one iteration#
continue jumps straight back to the top of the loop for the next item. The rest of the body is skipped only for this round.
Filtering bad data with continue#
break और continue में फर्क:
break= "बस, अब loop से बाहर निकलो।" बाकी बचे सारे iterations छोड़ दिए जाते हैं।continue= "यह वाला round छोड़ दो, अगले round पर जाओ।" Loop चलता रहता है।
उदाहरण: कक्षा में attendance लेते समय -
- अगर principal आ जाएं और class खत्म करनी पड़े → break
- अगर कोई student absent है तो उसका नाम छोड़कर अगले पर जाएं → continue
break and continue in nested loops#
They only affect the innermost loop:
To exit both loops, use a flag variable:
Loop else with break#
As you saw earlier, a loop's else runs only if no break happened - perfect for search problems:
pass - the placeholder#
Python doesn't allow empty blocks. pass fills the gap while you plan your code:
for student in students:
pass # TODO: send report card
def calculate_tax(amount):
pass # will write later
class Invoice:
pass
pass vs continue: in a loop, pass does nothing and the code after it in the same iteration still runs. continue skips the rest of the iteration.
for i in range(3):
if i == 1:
pass
print(i) # prints 0 1 2
Summary#
breakexits the nearest loop immediately.continueskips to the next iteration of the nearest loop.passdoes nothing - it is a placeholder for empty blocks.- A loop's
elseruns only when the loop wasn't broken - ideal for searches.