How is continue different from break?

Question

How does the behavior of the continue statement differ from the break statement?

Answer

The continue statement interrupts the execution of a loop and causes the loop to start the next iteration. Any code following the continue is not executed but the loop will continue on starting with the next iteration. The break statement will terminate the execution of the loop. No further code in the loop will execute and the program will resume execution at the next statement following the end of the loop.

In the following code example, if the counter is an even number, a continue statement is used to skip printing the number and continue to the next number. An if statement checks if counter has reached 19 and then uses a break to stop the execution of the loop. This code will print the odd numbers from 1 through 17.

counter = 0
while counter < 100:
    counter += 1
    
    # If number is even - skip to next
    if counter % 2 == 0:
        continue

    if counter == 19:
        break
        
    print(counter)
9 Likes

Thanks,Well explained!

2 Likes

Whether continue and break must be used with if.

Im unable to see the point of using “continue”

is it not just easier to us this formula?

for age in ages:
if age >= 21:
print(age)

3 Likes

Hi, there
Exactly what I did :sweat_smile:
But I think this is just an easy task to use ‘continue’.

1 Like

What if you break at 20? Does continue skips break in this case?

counter = 0
while counter < 100:
    counter += 1
    
    # If number is even - skip to next
    if counter % 2 == 0:
        continue

    #since continue skips even numbers, does that mean this break will be skipped too, and it will continue to print odd numbers after 20?
    if counter == 20:
        break
        
    print(counter)

Yes, because it is even so the loop continues in the line above it. This can be fixed by testing for 20, first, then test for even parity. You may as well print the counter when you increment it.

1 Like