Please explain the continue statement

312 views Asked by At

Please can anyone explain the continue statement, I have been trying my best to break it down to my understanding but all efforts have been futile. Here is a sample program I found in the python docs and I can't understand it.

for num in range(2, 10):
    if num % 2 == 0:
        print("Found an even number", num)
        continue
    else:
        print("Found a number", num)
1

There are 1 answers

4
Eli Bendersky On BEST ANSWER

The continue statement causes Python to skip the rest of the current iteration of the loop, and jump to the beginning of the next iteration.

See this documentation page for Python 3. The original example on that page is:

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found a number", num)

Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

When continue is encountered, the print at the end of the loop is skipped, and execution goes to the for again to get the next iteration. Note how for even numbers, "Found an even number" is printed, but "Found a number" is not printed. This is because the continue skipped the rest of the loop body.


Your modification to the sample - inserting the else - makes the continue obsolete, because the print("Found a number", num) wouldn't be executed anyway (it sits in an else) branch.

This way you've discovered that continue (and also break) are often an alternative control flow mechanism to if...else. Which to use depends on the situation and style preferences.