Skip to main content

Foundations of Python Programming: Functions First

Section 6.4 Break and Continue

Python provides ways for us to control the flow of iteration with a two keywords: break and continue.
break allows the program to immediately ‘break out’ of the loop, regardless of the loop’s conditional structure. This means that the program will then skip the rest of the iteration, without rechecking the condition, and just goes on to the next outdented code that exists after the whole while loop.
We can see here how the print statement right after break is not executed. In fact, without using break, we have no way to stop the while loop because the condition is always set to True!
continue is the other keyword that can control the flow of iteration. Using continue allows the program to immediately “continue” with the next iteration. The program will skip the rest of the iteration, recheck the condition, and maybe does another iteration depending on the condition set for the while loop.
Try stepping through the above code in codelens to watch the order that the code is executed in. Notice in the first iteration how the program doesn’t move to evaluate the divisible by 3 statment or add 1 to x. Instead, it continues to the next iteration.
You have attempted of activities on this page.