Controlling Loops Using Break and Continue
As a rule, for and while loops execute all the statements in their body on each iteration. However, sometimes it is handy to be able to break that rule. Python provides two ways of controlling the iteration of a loop: break, which terminates execution of the loop immediately, and continue, which skips ahead to the next iteration.
The Break Statement
In Repetition Based on User Input, we showed a program that continually read input from a user until the user typed quit. Here is a program that accomplishes the same task, but this one uses break to terminate execution of the loop when the user types quit:
| while True: |
| text = input("Please enter a chemical formula (or 'quit' to exit): ") |
| ... |
Get Practical Programming, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.