In Python it is used to skip the rest of the code inside a loop for the current iteration and immediately move on to the next iteration. Unlike the break
statement, which stops the loop entirely, continue
just skips to the next cycle of the loop.
Example:
Suppose you have a loop that prints numbers from 1 to 5, but you want to skip printing the number 3.
for i in range(1, 6):
if i == 3:
continue # Skip the rest of the loop when i is 3
print(i)
Explanation:
- The loop starts at 1 and goes up to 5.
- When ‘
i
‘ equals 3, theif
condition ‘i == 3
‘ becomes ‘True
‘. - The ‘
continue
‘ statement is executed, so the code after ‘continue
‘ (i.e., ,print(i)
‘) is skipped for this iteration. - The loop then continues with the next iteration.
Output:
1
2
4
5
In this example, the number 3 is not printed because when ‘i
‘ is 3, the ‘continue
‘ statement skips that iteration, moving directly to the next number.