How is continue different from break?


#1

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)