Line At A Time
Lesson 22: Continue
Continue Skip one trip around a loop with continue.
1for number in range(1, 6):
2 if number == 3:
3 continue
4 print(number)
Terminal
$ python3 main.py
1
2
4
5
Every line, explained
for number in range(1, 6):
range can take TWO numbers: range(1, 6) counts 1, 2, 3, 4, 5: it starts at the first number and stops just before the second.
if number == 3:
if checks the condition after it. Two things to notice: the line ends with a colon :, and the lines that belong to the if are indented 4 spaces underneath. Python uses indentation to know exactly which code is "inside" the if. If the condition is True the indented code runs; otherwise Python skips it. (The editor indents for you here; in a real editor you would type the 4 spaces.) We single out the moment number is 3.
continue
continue skips the REST of this trip around the loop and jumps straight to the next number. When number is 3, the print below never happens, so 3 is missing from the output.
print(number)
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Prints 1, 2, 4 and 5, but not 3, because continue skipped past this line that time.