Python continue Keyword
To continue to the next iteration of a loop. Placing this keyword in a loop skips everything
after the continue statement in the nearest for
or while
loop.
Example of a continue
in a for
loop:
Python
Copy Code
for x in range(5): if (x == 3): print("We're going to skip 3") continue print(x)
Output
0 1 2 We're going to skip 3 4
Example of a continue
in a while
loop:
Python
Copy Code
x = 0 while x < 5: if (x == 3): x = x + 1 # if we don't increment x, the loop will go forever! continue # skip the rest of the loop print(x) x = x + 1
Output
0 1 2 4
Notes
Notice in the while
loop, when x == 3, we still have to increment x, otherwise the while
loop will never end! The for
loop increments x for us.