Break, Continue and Pass statements using for loops in Python

In programming, for loops are used to automate repetitive tasks, such as analysing similar datasets from different subjects. Sometimes, a dataset might be slightly different to another such that the data can be used but needs to be analysed differently in the loop. For example, data might have been accidentally sampled at a higher rate, or a nested trial needs to be excluded. We can use conditional statements (ie. if, else or elif) and break, continue or pass statements in a for loop to handle exceptions differently. What are the differences in how break, continue or pass statements treat loop variables, and how might these statements be used?

Let’s use an if statement inside a for loop to detect the underscore _ in the string quick_brown_fox, and implement a break, continue or pass statement before printing out the letters in the string to see what happens:

1) When break is used, Python exits the for loop if a condition is satisfied.

for letter in 'quick_brown_fox':
    if letter == '_':
        break
    print(letter)
print('\nfinish loop')

q
u
i
c
k

finish loop

When the underscore _ was detected, the other letters from _ onwards were not printed.

2) When continue is used, Python ignores part of a for loop if a condition is satisfied, but proceeds to complete the rest of the loop:

for letter in 'quick_brown_fox':
    if letter == '_':
        continue
    print(letter)
print('\nfinish loop')

q
u
i
c
k
b
r
o
w
n
f
o
x

finish loop

When the underscore _ was detected, Python did not print _ but continued to print the rest of letters in the string. continue could be used to ignore exceptions for a subset of the dataset but analyse the remainder as per protocol.

3) When pass is used, Python ignores the condition and continues to execute the for loop as usual.

for letter in 'quick_brown_fox':
    if letter == '_':
        pass
    print(letter)
print('\nfinish loop')

q
u
i
c
k
_
b
r
o
w
n
_
f
o
x

When the underscore _ was detected, Python ignored the exception, printed _ and continued to print the rest of the letters in the string. pass could be used (with try and except statements) to ignore low level errors or warnings that do not affect the analysis, or as a placeholder when working on new code.

Summary

If a condition is satisfied in a for loop, break will exit a loop, continue ignores part of the loop but completes the rest of it, and pass ignores the condition and completes the whole loop. Use these statements to handle exceptions differently within loops. See this good explanation too on numerical examples using break, continue and pass.

 

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s