When should I use the 'continue' keyword?
Can't understand "Continue" function in Python statement(for loop, while loop) !!
Is there a difference between "pass" and "continue" in a for loop in Python? - Stack Overflow
Example use of "continue" statement in Python? - Stack Overflow
Videos
So, I tried searching the group and I found people asking *what* the continue keyword does, which is not my question. I think I understand it. Basically, it just says "hey, if x condition is met do not do what you did to every other element in the loop. Potentially do this instead or Just go to the next item."
The question I have is why should I use it instead of just an if-esle statement,, or if you prefer continue why should I use an if-else and not default to continue.
To put it into context, what is the meaningful difference between the following code blocks:
for i in range(10):
if i == 7:
print('7? I hate prime numbers bigger than 5!')
continue
print(f'Woo! I love the number {i}')and
for i in range(10):
if i == 7:
print('7? I hate prime numbers bigger than 5!')
else:
print(f'Woo! I love the number {i}')Both got me the same result. Is it just a "Python has many ways to do the same thing" deal or am I missing a crucial difference?
I am new to learning Python or rather I say new to programming. So, anyway
Can anyone help me understanding the "continue" function in Python statement(for loop while loop etc) or help me with a link with broad explanation?
I get "break" , "pass" but can't quite understand the use of "continue".
Yes, they do completely different things. pass simply does nothing, while continue goes on with the next loop iteration. In your example, the difference would become apparent if you added another statement after the if: After executing pass, this further statement would be executed. After continue, it wouldn't.
>>> a = [0, 1, 2]
>>> for element in a:
... if not element:
... pass
... print(element)
...
0
1
2
>>> for element in a:
... if not element:
... continue
... print(element)
...
1
2
Yes, there is a difference. continue forces the loop to start at the next iteration while pass means "there is no code to execute here" and will continue through the remainder of the loop body.
Run these and see the difference:
for element in some_list:
if not element:
pass
print(1) # will print after pass
for element in some_list:
if not element:
continue
print(1) # will not print after continue
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 skips the rest of the current iteration (here: print) and 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.
for ii in range(200):
for jj in range(200, 400):
...block0...
if something:
break
else:
...block1...
Break will break the inner loop, and block1 won't be executed (it will run only if the inner loop is exited normally).
for i in ...:
for j in ...:
for k in ...:
if something:
# continue loop i
In a general case, when you have multiple levels of looping and break does not work for you (because you want to continue one of the upper loops, not the one right above the current one), you can do one of the following
Refactor the loops you want to escape from into a function
def inner():
for j in ...:
for k in ...:
if something:
return
for i in ...:
inner()
The disadvantage is that you may need to pass to that new function some variables, which were previously in scope. You can either just pass them as parameters, make them instance variables on an object (create a new object just for this function, if it makes sense), or global variables, singletons, whatever (ehm, ehm).
Or you can define inner as a nested function and let it just capture what it needs (may be slower?)
for i in ...:
def inner():
for j in ...:
for k in ...:
if something:
return
inner()
Use exceptions
Philosophically, this is what exceptions are for, breaking the program flow through the structured programming building blocks (if, for, while) when necessary.
The advantage is that you don't have to break the single piece of code into multiple parts. This is good if it is some kind of computation that you are designing while writing it in Python. Introducing abstractions at this early point may slow you down.
Bad thing with this approach is that interpreter/compiler authors usually assume that exceptions are exceptional and optimize for them accordingly.
class ContinueI(Exception):
pass
continue_i = ContinueI()
for i in ...:
try:
for j in ...:
for k in ...:
if something:
raise continue_i
except ContinueI:
continue
Create a special exception class for this, so that you don't risk accidentally silencing some other exception.
Something else entirely
I am sure there are still other solutions.