Continue Statement
Now let's look at the continue
statement, which allows us to skip the rest of the current loop iteration and continue with the next iteration. Imagine you go running every day, but some days the weather is bad and you don't want to run. The continue
statement allows you to skip such days and continue running on the other days.
An iteration refers to one pass through the loop.
For example, we want to print all numbers between 1 and 10 except those that are multiples of 3:
number = 1
while number <= 10:
if number % 3 == 0: # If the number is a multiple of 3
number = number + 1
continue # Skip this iteration
print(number)
number = number + 1
# This will print: 1 2 4 5 7 8 10
In this example, we go through numbers from 1 to 10. If number
is a multiple of 3, we increase it by 1 and skip its printing using the continue
statement and move to the next iteration of the loop. If number
is not a multiple of 3, we print it and increase it by 1. It is important to realize that once the program encounters the continue
statement, it skips the rest of the statements in the loop's code block and continues with the next iteration. Let's go through a few iterations to make everything clear:
- The loop starts, and the value of
number
is 1. - The condition is skipped as
number
is not a multiple of 3. number
(value 1) is printed.number
is increased by 1.- We go back to the beginning of the loop. Now the number is 2.
- The condition is skipped as
number
is not a multiple of 3. number
(value 2) is printed.number
is increased by 1.- We go back to the beginning of the loop. Now the number is 3.
- The condition is met, so
number
is increased by 1. - The rest of the iteration is skipped.
- We go back to the beginning of the loop. Now the number is 4.
- …
Instructions
Using a while
loop, go through count
from 1 to 10 and print count
when it is not a multiple of 2. Use the continue
statement to skip numbers that are multiples of 2. Don't forget to increase the count
variable by 1.
Start programming for free
5/8