10.5. Break and Continue¶
Python provides ways for us to control the flow of iteration with 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 Python interpreter will exit the loop, skipping over any code below the break statement in the body of the loop, and move on
to the next outdented code that exists after the 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!
Here is a more realistic example of the use of a break statement:
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 do more iterations 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.
Here is the inventory example from above, but this time we don’t add the count of items to the inventory list if the count is 0:
Note that when you run the above code if you enter the name of an item and then enter the number of that item as 0 (or negative), it does not add an amount to the inventory list, or to the total quantity of items.