Controlling loops: the continue and break statements
The work of a loop can be controlled not only by the loop condition. The break operator ends the loop at once and the program continues from the line after the loop; it is usually written inside an if. continue throws away the rest of the current iteration and goes to the next turn of the loop, and the loop does not stop. For example, to accept words until the user types “stop”, while True: is written and break is done when “stop” comes: here the number of repetitions need not be known beforehand. A separate topic is swapping values. In other languages a third variable is needed, but in Python it is enough to write a, b = b, a: first the right side is calculated and then the values are given to the names on the left. So in a, b = b, a + b both expressions are calculated with the old values.
| What it does | |
|---|---|
| break | ends the loop at once |
| continue | skips the rest of the current iteration and goes to the next |
A pupil looking for their own name on the printed list for a trip stopped reading as soon as the name was found. There was no need to read the other lines, which is the idea of break.
Programmers, librarians and search staff stop checking when the needed item is found or skip unneeded items.
Write a list of ten numbers on paper and stop at the first one greater than 7. At which step did you stop, and why?
1while True: 2 w = input() 3 if w == "stop": 4 break 5 print(len(w))
4 5
1for i in range(1, 11): 2 if i % 3 == 0: 3 continue 4 print(i, end=" ") 5 6a, b = 1, 2 7a, b = b, a 8print(a, b)
1 2 4 5 7 8 10 2 1
“Exchange”: two pupils show a, b = b, a live with cards (values) in their hands; then they carry out a, b = b, a + b three times in a row and watch the result.
1for i in range(1, 8): 2 if i == 5: 3 break 4 print(i, end=" ")