Lessons 46 · 1 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
46
Controlling loops: the continue and break statements
Textbook: pp. 89–91
GoalTells the jobs of the break and continue operators apart, ends a while True: loop correctly with break, and swaps the values of two variables in the form a, b = b, a.
New words
break: leaves the loop at once · breakcontinue: skips the rest of the current pass and goes to the next iteration · continuewhile True: a loop that stops only by break · while Truea, b = b, a: swaps the values of two variables in one line · a, b = b, a
Explanation
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.
Worked examples
Stopping with break: while True: ⏎ w = input() ⏎ if w == "stop": ⏎ break ⏎ print(len(w)) If olma, kitob and stop are typed, 4 and 5 are printed; when stop comes the loop ends and its length is not printed.
Skipping with continue: for i in range(1, 11): ⏎ if i % 3 == 0: ⏎ continue ⏎ print(i, end=" ") Multiples of 3 are not printed: 1 2 4 5 7 8 10. Swapping: a, b = 1, 2 ⏎ a, b = b, a ⏎ print(a, b) 1 and 2 change places: 2 1.
Class activity
“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.
Practice
1
What does this program print? for i in range(1, 8): ⏎ if i == 5: ⏎ break ⏎ print(i, end=" ")
1 2 3 4
2
Write a program with continue that finds the sum of the numbers from 1 to 20 that are not multiples of 5.
s = 0 ⏎ for i in range(1, 21): ⏎ if i % 5 == 0: ⏎ continue ⏎ s += i ⏎ print(s) Answer: 160.
3
After a, b = 3, 9, if a, b = b, a + b is carried out, what are a and b?
a = 9, b = 12
4
Why must a while True: loop contain a break?
The condition is always true, so without break the loop never ends.