Example use of "continue" statement in Python? Example use of "continue" statement in Python? python python

Example use of "continue" statement in Python?


Here's a simple example:

for letter in 'Django':        if letter == 'D':        continue    print("Current Letter: " + letter)

Output will be:

Current Letter: jCurrent Letter: aCurrent Letter: nCurrent Letter: gCurrent Letter: o

It continues to the next iteration of the loop.


I like to use continue in loops where there are a lot of contitions to be fulfilled before you get "down to business". So instead of code like this:

for x, y in zip(a, b):    if x > y:        z = calculate_z(x, y)        if y - z < x:            y = min(y, z)            if x ** 2 - y ** 2 > 0:                lots()                of()                code()                here()

I get code like this:

for x, y in zip(a, b):    if x <= y:        continue    z = calculate_z(x, y)    if y - z >= x:        continue    y = min(y, z)    if x ** 2 - y ** 2 <= 0:        continue    lots()    of()    code()    here()

By doing it this way I avoid very deeply nested code. Also, it is easy to optimize the loop by eliminating the most frequently occurring cases first, so that I only have to deal with the infrequent but important cases (e.g. divisor is 0) when there is no other showstopper.


Usually the situation where continue is necessary/useful, is when you want to skip the remaining code in the loop and continue iteration.

I don't really believe it's necessary, since you can always use if statements to provide the same logic, but it might be useful to increase readability of code.