September 2013
Intermediate to advanced
350 pages
9h 38m
English
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.
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): ") |
| | ... |
Read now
Unlock full access