187

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?

Worm
  • 1,313
  • 2
  • 11
  • 28
JohnG
  • 2,109
  • 3
  • 16
  • 12

10 Answers10

232

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Snehal Parmar
  • 5,453
  • 3
  • 35
  • 46
  • 1
    I've been thinking for the past three or four days, why would I ever need a 'continue' statement and then I run into this post which in turn helps me with some QA — many thanks! – Freddy Mar 10 '16 at 05:56
  • 3
    same here, when we write python script (for cron job) and iterating on large values and some exception occurs then cron job will be stopped and you only be able to know that the next day, it really helps a lot in those case, Yes we can write send mail feature on exception but still the execution will be stopped. – Snehal Parmar Mar 10 '16 at 07:21
  • 9
    This illustrates what `continue` does but it's not overly useful, when you could do `if letter != 'D': print 'Current Letter:', letter` – Chris_Rands Sep 26 '18 at 21:56
  • I would have chosen Pray / remove r, or Fast / remove s. – Benjamin Crouzier Jan 07 '19 at 22:44
109

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.

Lauritz V. Thaulow
  • 49,139
  • 12
  • 73
  • 92
  • 2
    So "continue" is used mostly for readability by reducing indentation. I am wondering if "continue" adds any expressive power. – JohnG Dec 07 '11 at 19:49
  • 15
    Using `continue` in this fashion is similar to using `GOTO`. However, this is the _right_ way to use `GOTO`. – dotancohen Jun 10 '13 at 09:30
  • 2
    @JohnG I don't believe there is any use of continue (or break, for that matter) that cannot be reproduced without it, although not having it can be expensive in run-time. – Sparr Jul 14 '14 at 15:27
19

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.

pcalcao
  • 15,789
  • 1
  • 44
  • 64
  • 27
    note that using `if : continue` rather than `if not : ...` avoids a level of indentation that would otherwise be needed if it was written without it. – Dan D. Dec 07 '11 at 18:52
  • 1
    I was about to post a similar qn to JohnG but then found that he had already asked what I wanted to know. Reading through all the responses here has helped, but I still need to be sure about one thing - so is it that whenever we use a `continue` statement, we are essentially jumping out of a conditional testing section and allowing the iteration of the loop to proceed on to the next iteration? It isn't apparent to me how this would be better than using `else`. Is it just all about improved readability and run-time performance? – AKKO Dec 05 '14 at 02:44
  • "I don't believe it's necessary" ... well, python creators thought otherwise. – Jean-François Fabre Sep 14 '17 at 21:39
13
import random  

for i in range(20):  
    x = random.randint(-5,5)  
    if x == 0: continue  
    print 1/x  

continue is an extremely important control statement. The above code indicates a typical application, where the result of a division by zero can be avoided. I use it often when I need to store the output from programs, but dont want to store the output if the program has crashed. Note, to test the above example, replace the last statement with print 1/float(x), or you'll get zeros whenever there's a fraction, since randint returns an integer. I omitted it for clarity.

nutship
  • 4,624
  • 13
  • 47
  • 64
user1871712
  • 175
  • 1
  • 4
10

Some people have commented about readability, saying "Oh it doesn't help readability that much, who cares?"

Suppose you need a check before the main code:

if precondition_fails(message): continue

''' main code here '''

Note you can do this after the main code was written without changing that code in anyway. If you diff the code, only the added line with "continue" will be highlighted since there are no spacing changes to the main code.

Imagine if you have to do a breakfix of production code, which turns out to simply be adding a line with continue. It's easy to see that's the only change when you review the code. If you start wrapping the main code in if/else, diff will highlight the newly indented code, unless you ignore spacing changes, which is dangerous particularly in Python. I think unless you've been in the situation where you have to roll out code on short notice, you might not fully appreciate this.

C S
  • 1,363
  • 1
  • 17
  • 26
5
def filter_out_colors(elements):
  colors = ['red', 'green']
  result = []
  for element in elements:
    if element in colors:
       continue # skip the element
    # You can do whatever here
    result.append(element)
  return result

  >>> filter_out_colors(['lemon', 'orange', 'red', 'pear'])
  ['lemon', 'orange', 'pear']
ILYA Khlopotov
  • 705
  • 3
  • 5
  • 6
    But what does the `continue` statement _add_ here? It could be eliminated by using `element not in colors`, and the code would be just as readable. – ekhumoro Dec 07 '11 at 19:13
4

Let's say we want to print all numbers which are not multiples of 3 and 5

for x in range(0, 101):
    if x % 3 ==0 or x % 5 == 0:
        continue
        #no more code is executed, we go to the next number 
    print x
rassa45
  • 3,482
  • 1
  • 29
  • 43
  • You could also just use `if x %3 == 0 or x % 5 == 0:`, `pass`, `else:`, `print x` – Wildcard Aug 29 '16 at 23:39
  • 1
    Correct way is to either use continue or the not operator. Why unnecessarily use pass? – rassa45 Aug 30 '16 at 01:29
  • I like your way better (hence the upvote). I came to this page trying to sort out if there is ever a *need* to use `continue`. My conclusion is that there is never a *need*, but in some cases (like this one) the code is more readable using `continue`. It's a very good example. – Wildcard Aug 30 '16 at 01:39
4

It is not absolutely necessary since it can be done with IFs but it's more readable and also less expensive in run time.

I use it in order to skip an iteration in a loop if the data does not meet some requirements:

# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]

for time in commit_times:
    hour = time[0]
    minutes = time[1]

    # If the hour is not between 0 and 24
    # and the minutes not between 0 and 59 then we know something is wrong.
    # Then we don't want to use this value,
    # we skip directly to the next iteration in the loop.
    if not (0 <= hour <= 24 and 0 <= minutes <= 59):
        continue

    # From here you know the time format in the tuples is reliable.
    # Apply some logic based on time.
    print("Someone commited at {h}:{m}".format(h=hour, m=minutes))

Output:

Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45

As you can see, the wrong value did not make it after the continue statement.

Bastian
  • 5,625
  • 10
  • 44
  • 68
2

Here is a very good visual representation about continue and break statements

Continue example

source

mustafa candan
  • 567
  • 5
  • 16
-1

For example if you want to do diferent things depending on the value of a variable:

my_var = 1
for items in range(0,100):
    if my_var < 10:
        continue
    elif my_var == 10:
        print("hit")
    elif my_var > 10:
        print("passed")
    my_var = my_var + 1

In the example above if I use break the interpreter will skip the loop. But with continueit only skips the if-elif statements and go directly to the next item of the loop.

mahyard
  • 1,230
  • 1
  • 13
  • 34
jonathan.hepp
  • 1,603
  • 3
  • 15
  • 21
  • 3
    your example will never print anything, as the first condition is always true. assuming an initial value for `my_var` of `0`. – Dan D. Dec 07 '11 at 18:59
  • I simply adapted an example of an old code of mine. The original value of the var is not 0 and the increasing part was added for convenience as its original place wasn't there. Since it is an example and its value doesn't really matters I guess it's ok. – jonathan.hepp Dec 07 '11 at 19:06
  • 10
    It's not OK. It's not a good advertisement for using `continue`. – John Machin Dec 07 '11 at 19:19
  • 3
    And the first `elif` should be an `if`. The code just doesn't give the appearance that you know what you are doing. – John Machin Dec 07 '11 at 19:24
  • this is a bad example – patrick Mar 30 '18 at 14:35