Search code examples
pythonloopscontinue

Python 3 Use case for continue instead of not (!=)


So I'm learning Python finally and I've just learned about skipping to the next iteration of a loop using continue. Now my question is, what would be a real world use case for continue instead of not or != ?

Consider the three pieces of simple code below:

for i in range(0, 10):
    if i == 3:
        continue
    print(i)

for i in range(0, 10):
    if i != 3:
        print(i)

for i in range(0, 10):
    if i == 3:
        log()
    print(i)

In my mind, I don't see why I should prefer the first to the second. I found another question regarding continue, and someone mentioned about using it when they wanted to log something, but in that case, why not use the third example?

I fully understand that for such a simple example as I've given, the difference probably isn't much but could someone tell me when I should prefer continue? Or is it just more of a "avoiding the use of !=" case?


Solution

  • continue for a loop is just like return to a function: a convenience instruction to skip to the next iteration right now.

    On a complex case, continue can skip to the next iteration very simply:

    for i in range(0, 10):
        if i != 3:
            print("something")
            if my_function(i) != 34:
               continue
        print(i)
    

    To do that without continue, you need a flag or else conditions. Careful as if there are a lot of continue statements in your loops it can become difficult to debug (just like when you put too many return statements in a function)