Lessons 44–45 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
44
Programming repeating algorithms: the while statement
Textbook: pp. 86–88
GoalKnows the while loop and its structure, solves tasks with an unknown number of repetitions by a condition, remembers to change the loop condition, and recognises and stops an infinite loop.
New words
while: a loop that repeats its body as long as its condition is True · whileloop condition: the bool expression checked before every pass · sikl shartiinfinite loop: a loop whose condition never becomes False · cheksiz siklCtrl + C: the keys that interrupt a running program in IDLE · Ctrl + C
Explanation
for is handy when the number of repetitions is known beforehand; if it is unknown, while is used. It is written while condition: with the loop body on the next line indented by 4 spaces. Python first checks the condition: if it is True the body is run and it goes back to the condition, if it is False the loop ends; if the condition is False from the very start the body does not run even once. So the loop variable must be given a starting value before the loop and be changed in the body: i += 1 or typing a new number. If the condition never becomes False, the loop goes on forever; in IDLE it can be stopped with the Ctrl + C keys. while True: is also an infinite loop. Do not write an infinite loop on purpose; if you made one by mistake, stop it.
Worked examples
Counting: i = 1 ⏎ while i <= 5: ⏎ print(i, end=" ") ⏎ i += 1 It runs while i <= 5 is true and stops when i becomes 6. An unknown number: s = 0 ⏎ n = int(input()) ⏎ while n != 0: ⏎ s += n ⏎ n = int(input()) ⏎ print(s) If 4, 6, 10 and 0 are typed, 0 is not added and 20 is printed.
Powers of 2: p = 1 ⏎ while p < 100: ⏎ print(p, end=" ") ⏎ p *= 2 The screen shows 1 2 4 8 16 32 64: when p reaches 128 the condition p < 100 is false and the loop stops. How many turns there will be is not said in advance – the condition decides it.
Class activity
“Watch the condition”: the group draws a trace table of a while program on the board (step, variable values, condition) and runs it by hand; then it compares with the result in IDLE.
Practice
1
How many times does this loop turn? i = 10 ⏎ while i > 0: ⏎ i -= 3
4
2
Write a program that finds the first (leftmost) digit of a number with while (4 for 45678).
x = int(input()) ⏎ while x >= 10: ⏎ x //= 10 ⏎ print(x)
3
Why does this program run forever, and how is it fixed? i = 1 ⏎ while i < 5: ⏎ print(i)
i never changes, so the condition is always true. i += 1 must be added to the body with the same indent as print(i).
4
When is while chosen instead of for?
When the number of repetitions is not known beforehand and the loop stops by a condition.