Practical lesson: the while statement
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.
A school club counted digits in numbers to see how often each appeared. Each time they took off the last digit and shortened the number. The result was clear in a table.
Researchers, cryptography learners and programmers break numbers into digits to analyse them.
Choose three numbers with three or four digits, find each digit sum on paper, and check whether a number and its digit sum are divisible by 3 together or not at all.
1x = int(input()) 2s = 0 3while x > 0: 4 s += x % 10 5 x //= 10 6print(s)
22
1guess = int(input()) 2while guess != 7: 3 print("Yana urining") 4 guess = int(input()) 5print("Topdingiz")
Yana urining Yana urining Topdingiz
“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”.