The continue Statement
The continue statement is the smaller sibling of break. It doesn't end the whole loop, only the current iteration: it skips the rest of the block, and the loop goes straight on to the next iteration.
This loop prints the numbers from 1 to 10, but skips the multiples of 3:
for number in range(1, 11):
if number % 3 == 0:
continue
print(number)This prints:
1
2
4
5
7
8
10For 3, 6 and 9, the condition is true, and continue skips the print(number) below it. The loop then carries on as usual with the next number from range().
The continue statement usually sits at the beginning of the block and filters out the elements you don't want to deal with: “this one doesn't interest me, on to the next one”. The rest of the block then only handles the interesting ones.
Be careful with continue in a while loop. It jumps straight back to the condition, so if the line that increases the counter is below continue, it is skipped too. The counter then never changes again, and the loop never ends. In a for loop, this can't happen: the list or range() gives the loop its next value every time.
Instructions
- 1
Before going shopping, you want to print only the things you don't have at home. Write a
forloop overshopping_list. At the start of its block, write anifthat skips the item withcontinuewhen it isinthe listat_home. - 2
After the
if, still inside the loop, printBuy:and the item. The output isBuy: milk,Buy: eggsandBuy: apples, each on its own line.