Theory 5 — WHILE LOOP AND DIGIT PROCESSING




Python Programming: The while Loop and Digit Processing. Repeating Actions Until a Condition Changes.

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 True or False).
  • 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.

Example 1: Printing «Hello» Ten Times
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 = 0 before the loop.
  • The loop body prints and then increments i.
  • When i reaches 10, the condition becomes false and the loop ends.
Example 2: A Loop That Never Runs
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.
  • while is 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.

Example 3: if vs while

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 for when you know the count.
  • Choose while when 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.

Example 4: Printing Numbers from 0 to 100

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.

Example 5: Printing Numbers Divisible by 3 up to 100

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

Example 6: Sequence 3, 5, 7, …, 21

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

Example 7: Sum and Product of Odd Two-Digit Integers

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».

Example 8: Reading Numbers until -1

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, num would never change, and the loop would run forever!
Example 9: Reading Strings until a Sentinel

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

Example 10: Counting Words until a Stop Word

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

Example 11: Divisibility by 7 with a Stop Condition

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).

Example 12: An Infinite Loop
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
Example 13: Printing Numbers 0 through 9 with a Post-Condition Loop
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.

Example 14: Finding the Maximum until Zero

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.

Example 15: Using and in a Condition
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

Example 16: Quotient and Remainder Using Only Addition and Subtraction

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

Example 17: Several Counters

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 % 10 gives us the last digit.
  • num // 10 removes 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:

  1. 123 % 10 → 3
  2. 123 // 10 → 12
  3. 12 % 10 → 2
  4. 12 // 10 → 1
  5. 1 % 10 → 1
  6. 1 // 10 → 0 (stop here!)
Example 18: The Digit Extraction Loop
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).

Example 19: Print Digits in a Column in Reverse Order

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:

  1. Read the integer n.
  2. Set up a while loop that runs as long as n is not zero.
  3. Inside the loop, n % 10 extracts the current last digit.
  4. print() displays it on a new line.
  5. n //= 10 removes the last digit, bringing the next digit into the "last" position.
  6. The loop repeats until n becomes 0.



➕ Sum, Product, and Count of Digits

Example 20: Sum of Digits
n = 123
total = 0
 
while n != 0:
    total += n % 10
    n //= 10
 
print("Sum of digits:", total)   # 6

Example 21: Product of Digits
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 (*=).

Example 22: Sum, Count, Product, Average, First Digit, and Sum of First and Last

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:

  1. Initialize total = 0, count = 0, product = 1. Store original = n.
  2. Loop: extract digits, add to total, increment count, multiply into product, remove the digit.
  3. Post-processing:
    • first_digit = original // (10 ** (count - 1)). Since count is 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.

Example 23: Reversing an Integer
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

Example 24: Finding the Largest and Smallest 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

Example 25: Are All Digits Identical?

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:

  1. Handle the n == 0 edge case.
  2. Store the last digit as a reference (last_digit). Remove it from n.
  3. Set a flag is_identical = True.
  4. Loop through the remaining digits. If any digit differs from last_digit, set the flag to False and break out of the loop.
  5. 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).

Example 26: Processing Digits from Left to Right with for
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.