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
45
Practical lesson: the while statement
Textbook: pp. 88–89
GoalIn the practical lesson, works with the digits of a number using while (sum, counting) and writes programs that repeat depending on the user’s answer.
New words
digit sum: add x % 10, then remove the last digit with x //= 10 · raqamlar yig‘indisiguessing game: the loop repeats until the guess matches · sinov-xato o‘yiniloop variable: the value changed in the body so that the condition can stop the loop · sikl o‘zgaruvchisitrace table: a table of the variable values after each pass · kuzatuv jadvali
Explanation
The best use of the while loop is working with the digits of a number. Digit sum: s = 0; the loop runs while x > 0; each time the last digit is added to s (x % 10) and removed from x (x //= 10). The same pattern is used to count digits, only k += 1 is put instead of s += x % 10. The second kind of task is asking until the answer is right: the first answer is asked before the loop, the condition is written as “the answer is wrong”, and in the body it is asked again and the answer is renewed. In this game the hidden number is given inside the program; a random number will be learned later (the random module). Run each program by hand in a trace table: then it is clear when the loop stops.
Worked examples
Digit sum: x = int(input()) ⏎ s = 0 ⏎ while x > 0: ⏎ s += x % 10 ⏎ x //= 10 ⏎ print(s) For 2749, 9 + 4 + 7 + 2 = 22 is printed.
Guessing: guess = int(input()) ⏎ while guess != 7: ⏎ print("Yana urining") ⏎ guess = int(input()) ⏎ print("Topdingiz") 3 and 9 are wrong, so “Yana urining” is printed twice; when 7 is typed the loop ends and “Topdingiz” is printed.
Class activity
“A game with digits”: pairs choose their own numbers, run the digit sum program in a trace table and compare the final answer with IDLE; then they change the program for the “product of digits”.
Practice
1
What is the sum of the digits of 5081?
14
2
Write a program that finds the sum of the numbers from 1 to n with while (55 for n = 10).
n = int(input()) ⏎ i = 1 ⏎ s = 0 ⏎ while i <= n: ⏎ s += i ⏎ i += 1 ⏎ print(s)
3
How many 0 digits are there in 40105? Write a program that counts them.
x = int(input()) ⏎ k = 0 ⏎ while x > 0: ⏎ if x % 10 == 0: ⏎ k += 1 ⏎ x //= 10 ⏎ print(k) Answer: 2.
4
Why does the digits loop never stop without x //= 10?
x does not change, so the condition x > 0 stays true; x //= 10 reduces x until it reaches zero.