Example use of "continue" statement in Python?
The definition of the continue
statement is:
The
continue
statement continues with the next iteration of the loop.
I can't find any good examples of code.
Could someone suggest some simple cases where continue
is necessary?
Here's a simple example:
for letter in 'Django':
if letter == 'D':
continue
print("Current Letter: " + letter)
Output will be:
Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current 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.