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)
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:
When
continue
is encountered, theprint
at the end of the loop is skipped, and execution goes to thefor
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 thecontinue
skipped the rest of the loop body.Your modification to the sample - inserting the
else
- makes thecontinue
obsolete, because theprint("Found a number", num)
wouldn't be executed anyway (it sits in anelse
) branch.This way you've discovered that
continue
(and alsobreak
) are often an alternative control flow mechanism toif...else
. Which to use depends on the situation and style preferences.