Skipping and stopping

Lesson 31 of 54 · Python Foundations

continue skips the rest of the current iteration and returns control to the loop for the next one. break exits the nearest enclosing loop entirely. Neither statement exits a function by itself.

for number in range(1, 7):
    if number % 2 == 0:
        continue
    print(number)
1
3
5

When number is even, the remainder after division by two is zero. continue skips the print for that value; the next value still arrives from the range.

for shelf in range(1, 6):
    print("Inspect", shelf)
    if shelf == 3:
        print("Found")
        break
print("Search ended")
Inspect 1
Inspect 2
Inspect 3
Found
Search ended

The print before break still happens on the third pass. Shelves 4 and 5 are never visited; execution resumes after the loop. In nested loops, break stops only the innermost loop containing it.

In a while loop, take care that continue does not skip an update needed for termination. A misplaced return inside a loop instead exits the entire function on its first reached iteration; put a final return after the loop when it must process all values.

Chapter index