Continue Statement in Python
The continue
statement in Python is used to skip the current iteration
of a loop and jump to the next one.
It is helpful when we want to ignore specific conditions but continue looping.
For example, we may want to skip printing a particular number in a sequence without stopping the loop.
Syntax:
for variable in sequence:
if condition:
continue
# block of code
Note: The loop does not stop; it just skips the remaining code for that cycle.
Example: Skip number 3
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
Explanation:
- The loop goes from 1 to 5 using
range(1, 6)
. - When the value of
i
becomes 3, thecontinue
statement is triggered. - This means Python skips the
print()
line for 3. - All other numbers (1, 2, 4, 5) are printed normally.
Example 2: Skip vowels while printing a name
name = "Devanshi"
for char in name:
if char in "aeiouAEIOU":
continue
print(char)
Output:
D
v
n
s
h
Explanation:
- The string
"Devanshi"
is looped character by character. - We check if the current character is a vowel (a, e, i, o, u).
- If it is a vowel, the
continue
statement is used to skip printing that character. - So only consonants (D, v, n, s, h) are printed, vowels are ignored.
Real-Life Example:
Think of checking students' homework. You check everyone's work, but if one student was absent, you skip them and move to the next — you don't stop checking.
Summary:
continue
is used to skip certain iterations inside a loop.- The loop keeps running after skipping.
- Useful for ignoring unwanted values or conditions.