while Loop and Digit Processing. Repeating Actions Until a Condition Changes.Содержание:
- Python Programming: The while Loop and Digit Processing
- 📑 Table of Contents
- 🔁 Why the while Loop?
- ⚙️ Syntax of the while Loop
- ⚖️ while vs if
- 🔄 for vs while — When to Use What?
- 🛑 The Sentinel Value Pattern
- ♾️ The Infinite Loop
- 🔂 Emulating a Post-Condition Loop
- 🧠 while Loop with Complex Conditions
- 🔢 Processing Digits — The Digit Extraction Loop
- ➕ Sum, Product, and Count of Digits
- 🔃 Reversing a Number
- 📊 Maximum and Minimum Digit
- 🪞 Checking for Identical Digits
- 🔄 Processing Digits with a for Loop
Python Programming: The while Loop and Digit Processing
Conditional Loops and Working with Digits | Repeating Actions Until a Condition Changes
🔁 Why the while Loop?
There are two main types of loops in Python:
- Counting loops (
for) — repeat a fixed number of times, when the number of iterations is known in advance. - Conditional loops (
while) — repeat until a certain event occurs, when the number of iterations cannot be estimated in advance.
The for loop works perfectly when we know how many repetitions we need. But sometimes a loop must run until some event happens, and the number of iterations is impossible to predict. This is where the while loop comes to the rescue.
The name while literally means «as long as»: the loop performs its task as long as the condition remains true.
Interesting fact: A while loop is a «0 or more times» loop — if the condition is false from the start, the body never executes.
⚙️ Syntax of the while Loop
while condition: # code block – the loop body |
Key elements:
- Keyword
while. - Condition (evaluates to
TrueorFalse). - Colon
:at the end of the first line. - Indented body (4 spaces).
The condition is checked before each iteration. If it is True, the body executes. If it is False, the loop stops. This is why while is called a pre-tested loop.
i = 0 while i < 10: print("Hello") i += 1 |
Output:
Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
Key points:
- We initialize
i = 0before the loop. - The loop body prints and then increments
i. - When
ireaches 10, the condition becomes false and the loop ends.
i = -1 while i > 0: print("Hello world!") |
No text is printed because the condition i > 0 is false from the very beginning. A while loop may execute zero times.
Important notes:
- A single execution of the loop body is called an iteration.
whileis a pre-test loop: the condition is checked before the body.
⚖️ while vs if
The while loop is very similar to the if statement. The difference is that the if block executes at most once, while the while block executes repeatedly as long as the condition is true.
if statement — executes once:
i = 0 if i < 10: print("Hello") |
while statement — executes repeatedly:
i = 0 while i < 10: print("Hello") i += 1 |
Key takeaway: The if block runs at most once; the while block runs until the condition becomes False.
🔄 for vs while — When to Use What?
| for loop (Counting) | while loop (Conditional) |
|---|---|
| «Repeat N times» — a known number of iterations; iterating over a sequence. | «Repeat until stopped» — an unknown number of iterations; waiting for a specific input or condition. |
Key takeaways:
- Choose
forwhen you know the count. - Choose
whilewhen you need to react to a condition.
We can always simulate a for loop with a while loop, but not always the other way around. If the number of iterations is not known in advance, only while will work.
Using a for loop:
for i in range(101): print(i) |
Using a while loop:
i = 0 while i < 101: print(i) i += 1 |
In the for loop the variable i is managed automatically. In the while loop we must create i ourselves, initialize it, and increment it inside the body.
Using a for loop:
for i in range(0, 100, 3): print(i) |
Using a while loop:
i = 0 while i < 100: print(i) i += 3 |
Task: Output the sequence 3 5 7 9 … 21 twice — with a while loop and with a for loop.
Using a for loop:
for i in range(3, 21 + 1, 2): print(i, end=" ") |
Using a while loop:
i = 3 while i <= 21: print(i, end=" ") i += 2 |
Output:
3 5 7 9 11 13 15 17 19 21
Task: Calculate the sum and the product of all odd two-digit integers: 11 + 13 + 15 + … + 99 and 11 × 13 × 15 × … × 99.
sum_ = 0 pr = 1 i = 11 while i <= 99: sum_ += i pr *= i i += 2 print(f"sum = {sum_} product = {pr}") |
Expected output:
sum = 2565 product = 26480481588727626724487930522894928519708555015404150532676018390356298828125
🛑 The Sentinel Value Pattern
A sentinel value is a special value that signals the end of the input. This pattern is very common when solving tasks with while loops: we read data until the user enters a particular value that means «stop».
Task: Read numbers and print their squares until -1 is entered.
num = int(input()) while num != -1: print(num * num) num = int(input()) |
Example run:
Input: 5 Output: 25 Input: 3 Output: 9 Input: -1 (Program ends)
Key takeaways:
- Initialization: the first number is read before the loop — it gives us the first value to check.
- Update: the next number is read at the end of the loop body. If we forgot this line,
numwould never change, and the loop would run forever!
Task: Sum numbers until the user types "stop".
text = input() total = 0 while text != "stop": num = int(text) total += num text = input() print("Sum of numbers is", total) |
Example run:
2 5 3 stop Sum of numbers is 10
Task: A sequence of words is provided on separate lines. The sequence ends when one of the words stop, enough, or quit appears. Those ending words are not counted. Output the total number of words in the sequence.
count = 0 word = input() while word != "stop" and word != "enough" and word != "quit": count += 1 word = input() print(count) |
Example run:
Skyrim GTA Mafia stop Battlefield 3
Task: Read integers divisible by 7, each on a separate line. The sequence ends as soon as a number that is not divisible by 7 appears. That terminating number is not part of the sequence — it only marks the end. Print all members of the sequence.
num = int(input()) while num % 7 == 0: print(num) num = int(input()) |
Example run:
49 2401 4809 0 2 10 100 Output: 49 2401 4809 0
The number 2 is not divisible by 7, so it stops the sequence and is not printed. Numbers after it are ignored.
♾️ The Infinite Loop
A while loop must, in almost all cases, contain the possibility of ending. Something inside the loop must eventually make the condition false. If the loop cannot finish, it is called an infinite loop. It repeats until the program is interrupted (usually by Ctrl + C, producing a KeyboardInterrupt).
i = 0 while i < 10: print("Hello") # Missing i += 1, i is never updated! |
The program prints "Hello" forever because i is never changed, and the condition i < 10 remains true.
Key takeaways:
- Infinite loops freeze your program.
- Always update the variables used in the condition inside the loop.
Interesting fact: In 1996 the Ariane 5 rocket exploded due to a software bug caused by a data overflow — a striking reminder of how dangerous an uncontrolled loop or overflow can be.
🔂 Emulating a Post-Condition Loop
A while loop checks the condition before the body runs. Sometimes, however, we need to execute the body at least once and then check the condition — a so-called post-condition loop. In Python this is emulated with an "infinite" loop plus a break statement.
while True: # loop body if exit_condition: break |
count = 0 while True: print(count) count += 1 if count >= 10: break |
Output:
0 1 2 3 4 5 6 7 8 9
The body executes at least once before the exit condition is checked. The break statement is covered in more depth in later lessons.
Task: Read numbers until 0 is entered and print the maximum.
maximum = -float('inf') while True: num = int(input("Enter a number (0 to exit): ")) if num == 0: break if num > maximum: maximum = num print("Maximum:", maximum) |
🧠 while Loop with Complex Conditions
The condition in a while loop can be as complex as in an if statement. Logical operators and, or, and not can be used.
name = input() while name != "Ivan" and name != "Arthur": print("Access Denied") name = input() print("Access Granted") |
Example run:
Maria Access Denied Olga Access Denied Oleg Access Denied Arthur Access Granted
Task: Positive integers N and K are given. Using only addition and subtraction, find the quotient and the remainder of dividing N by K.
n = int(input('n? ')) k = int(input('k? ')) quot = 0 while k <= n: n -= k quot += 1 print() print(f"quotient = {quot} remainder = {n}") |
Example run:
n? 15 k? 7 quotient = 2 remainder = 1
Task: A pupil has n grades from 2 to 5. Calculate how many grades of each value were received.
n = int(input("Enter the number of grades: ")) count_2, count_3, count_4, count_5 = 0, 0, 0, 0 i = 0 while i < n: grade = int(input(f"Enter grade {i + 1}: ")) if grade == 2: count_2 += 1 elif grade == 3: count_3 += 1 elif grade == 4: count_4 += 1 elif grade == 5: count_5 += 1 i += 1 print("Number of grades:") print(f"2 = {count_2}") print(f"3 = {count_3}") print(f"4 = {count_4}") print(f"5 = {count_5}") |
Example run:
Enter the number of grades: 5 Enter grade 1: 2 Enter grade 2: 3 Enter grade 3: 4 Enter grade 4: 2 Enter grade 5: 3 Number of grades: 2 = 2 3 = 2 4 = 1 5 = 0
🔢 Processing Digits — The Digit Extraction Loop
Given a positive integer num:
num % 10gives us the last digit.num // 10removes the last digit (integer division).
Using the while loop together with these two operations, we can process the digits of any number, regardless of how many digits it has.
Trace for num = 123:
123 % 10 → 3123 // 10 → 1212 % 10 → 212 // 10 → 11 % 10 → 11 // 10 → 0(stop here!)
n = int(input()) while n != 0: digit = n % 10 print(digit, end=' ') n = n // 10 |
Example run:
Input: 12345 Output: 5 4 3 2 1
Key takeaways: the standard pattern is extract, process, remove. The loop condition is n > 0 (or n != 0).
Task: Read a natural number and print its digits in a column in reverse order.
n = int(input()) while n != 0: print(n % 10) n = n // 10 |
Example run:
Input: 12345 Output: 5 4 3 2 1
Step-by-step explanation:
- Read the integer
n. - Set up a
whileloop that runs as long asnis not zero. - Inside the loop,
n % 10extracts the current last digit. print()displays it on a new line.n //= 10removes the last digit, bringing the next digit into the "last" position.- The loop repeats until
nbecomes 0.
➕ Sum, Product, and Count of Digits
n = 123 total = 0 while n != 0: total += n % 10 n //= 10 print("Sum of digits:", total) # 6 |
n = 123 product = 1 while n != 0: product *= n % 10 n //= 10 print("Product of digits:", product) # 6 |
Key takeaways: the sum uses addition (+=), the product uses multiplication (*=).
Task: Given a natural number, compute:
- the sum of its digits,
- the number of digits,
- the product of its digits,
- the average of its digits (as a float),
- its first digit,
- the sum of its first and last digit.
n = int(input()) original = n # keep the original for first/last calculation total = 0 count = 0 product = 1 while n != 0: digit = n % 10 total += digit count += 1 product *= digit n //= 10 # After the loop n is 0. Use the original to find the first digit. first_digit = original // (10 ** (count - 1)) last_digit = original % 10 average = total / count print("Sum:", total) print("Count:", count) print("Product:", product) print("Average:", average) print("First digit:", first_digit) print("Sum of first and last:", first_digit + last_digit) |
Example run (input: 5678):
Sum: 26 Count: 4 Product: 1680 Average: 6.5 First digit: 5 Sum of first and last: 13
Step-by-step explanation:
- Initialize
total = 0,count = 0,product = 1. Storeoriginal = n. - Loop: extract digits, add to
total, incrementcount, multiply intoproduct, remove the digit. - Post-processing:
first_digit = original // (10 ** (count - 1)). Sincecountis the number of digits,10 ** (count - 1)gives the highest place value (e.g.,5678 // 1000 = 5).last_digit = original % 10.- Average is
total / count.
🔃 Reversing a Number
Reversing a number means rebuilding it in reverse order. Each new digit is appended by multiplying the current result by 10 and adding the new digit.
n = int(input("Input: ")) reversed_n = 0 while n != 0: digit = n % 10 reversed_n = reversed_n * 10 + digit n //= 10 print("Output:", reversed_n) |
Example run:
Input: 123 Output: 321
Trace for n = 123:
- Iteration 1:
digit = 3,reversed_n = 0 × 10 + 3 = 3,n = 12 - Iteration 2:
digit = 2,reversed_n = 3 × 10 + 2 = 32,n = 1 - Iteration 3:
digit = 1,reversed_n = 32 × 10 + 1 = 321,n = 0
📊 Maximum and Minimum Digit
Task: Find the maximum and minimum digit of a number.
n = int(input()) max_digit = n % 10 min_digit = n % 10 n = n // 10 while n != 0: digit = n % 10 if digit > max_digit: max_digit = digit if digit < min_digit: min_digit = digit n = n // 10 print("Max digit:", max_digit) print("Min digit:", min_digit) |
Example run (input: 53258):
Max digit: 8 Min digit: 2
Important note about zero: if n = 0 initially, the loop will not run at all. If you need to process 0 as a number with one digit, handle the case separately or use while True with a break condition.
🪞 Checking for Identical Digits
Task: Determine whether a number consists of identical digits (e.g., 111 is YES, 112 is NO).
n = int(input()) if n == 0: print("YES") else: last_digit = n % 10 n //= 10 is_identical = True while n != 0: digit = n % 10 if digit != last_digit: is_identical = False break n //= 10 if is_identical: print("YES") else: print("NO") |
Example runs:
Input: 111111 Output: YES Input: 111112 Output: NO
Step-by-step explanation:
- Handle the
n == 0edge case. - Store the last digit as a reference (
last_digit). Remove it fromn. - Set a flag
is_identical = True. - Loop through the remaining digits. If any digit differs from
last_digit, set the flag toFalseandbreakout of the loop. - Print the result based on the flag.
🔄 Processing Digits with a for Loop
We can also process digits using a for loop, if we know how many digits the number has. This approach goes through the digits from left to right.
First, the number of digits is found using the length of the string representation:
n = len(str(num)) |
Then, each digit at position i (counting from 1, left to right) is extracted with the formula:
(num // 10 ** (n - i)) % 10 |
where n is the total number of digits and i is the position of the digit (starting at 1).
num = 8619 n = len(str(num)) for i in range(1, n + 1): digit = num // 10 ** (n - i) % 10 print(i, '-th digit is', digit) |
Output:
1 -th digit is 8 2 -th digit is 6 3 -th digit is 1 4 -th digit is 9
Comparison with the while loop: the while loop extracts digits from right to left (last digit first), while this for loop extracts them from left to right. Choose the approach that fits your task.