In Python, the continue
statement is used to skip the current iteration of a loop and proceed with the next one. Unlike break
, which exits the loop entirely, continue
simply jumps to the next iteration.
Usage of continue statement
continue
in a while
loop:
i = 0
while i < 10:
i += 1
if i % 2 == 0: # Skip even numbers
continue
print(i)
Explanation: The loop increments i
in each iteration, but when i
is even, the continue
the statement is triggered, skipping the rest of the loop body for that iteration. This prints only odd numbers.
continue
in a for
loop:
for i in range(1, 10):
if i == 5: # Skip the number 5
continue
print(i)
Explanation: The loop iterates through numbers from 1 to 10 but skips printing the number 5 due to the continue
statement.
continue
with if
conditions:
for char in "hello world":
if char == "o": # Skip when 'o' is encountered
continue
print(char)
Explanation: When the letter 'o'
is encountered in the string, the continue
statement skips printing it and moves to the next character.