The continue statement skips the remaining statements in the current loop iteration. Execution then returns to the loop’s beginning, checks the while condition again, or takes the next item in a for sequence. section 18.3 section 18.4
Filtering loop values
In a for loop, continue can reject values early: for x in range(100): print("x is", x) if x <= 5: continue print("x is greater than 5") if x % 10 == 0: continue print("x is not divisible by 10") Values from 0 through 5 skip the rest of the loop. Values divisible by 10 also skip the later statements. The loop then proceeds with the next x. section 18.3
Use continue when:
- Several conditions determine whether the main body should run. section 18.3
- You want to avoid deeply nested conditionals by handling unwanted cases first. section 18.3
- You need to skip work without stopping the innermost loop; use break when the loop itself should end. section 18.4
Listing 18.5. Comparing code that does and doesn’t use the continue keyword
### Version 1 of some code ###
x = 0
for x in range(100):
print("x is", x)
if x > 5:
print("x is greater than 5")
if x%10 != 0:
print("x is not divisible by 10")
if x==2 or x==4 or x==16 or x==32 or x==64:
print("x is a power of 2")
# perhaps more code
### Version 2 of some code ###
x = 0
for x in range(100):
print("x is", x)
if x <= 5:
continue #1
print("x is greater than 5") #2
if x%10 == 0:
continue #1
print("x is not divisible by 10") #3
if x!=2 and x!=4 and x!=16 and x!=32 and x!=64:
continue #1
print("x is a power of 2") #4
# perhaps more code
Compare nested-condition code with an equivalent version that uses continue to skip unwanted cases. section 18.3




