Continue and break statements

The "continue" Statement

The continue statement is used within loops (such as for or while loops) to skip the remaining code in the current iteration and move to the next iteration. It allows us to control the flow of the loop based on certain conditions.

Let's take an example of a for loop with a continue statement:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        continue
    print(num)

In this code, we have a for loop that iterates over the numbers list. When the value of num is equal to 3, the continue statement is encountered, and the remaining code in that iteration is skipped. The loop then moves to the next iteration.

Click the run button to see the output. You should see:

1
2
4
5

In this example, the number 3 is skipped due to the continue statement, and the loop continues with the next iteration.

The "break" statement

The break statement is used within loops to terminate the loop prematurely. It allows us to exit the loop entirely based on certain conditions.

Let's take an example of a while loop with a break statement:

count = 0

while True:
    print(count)
    count += 1
    if count == 5:
        break

In this code, we have a while loop that runs indefinitely (while True). Inside the loop, we print the value of count and increment it by 1. When the value of count becomes 5, the break statement is encountered, and the loop is terminated.

Click the run button to see the output. You should see:

0
1
2
3
4

In this example, the loop runs until the value of count reaches 5. At that point, the break statement is encountered, and the loop is terminated.

To run a block of code if the for loop never encounters a break statement, learn about the for-else structure.