Skip to main content
EDU-MMCS
You are currently using guest access (Log in)

Programming Fundamentals (Python)

  1. Home
  2. Courses
  3. Осенний семестр
  4. Python Eng
  5. Module 2: LOOPs
  6. Module 2.2 - The while Loop and Digit Processing

Module 2.2 - The while Loop and Digit Processing

Completion requirements

Python Programming: The while Loop and Digit Processing

📑 Table of Contents

  • 🔹 Lab 1 – Reverse Order
  • 🔹 Lab 2 – All Together
  • 🔹 Lab 3 – Identical Digits
  • 🔹 Lab 4 – Max and Min Digit
  • 🔸 Practice Exercises
  • 🔸 Answer Key

Laboratory Works (1 – 4)

Each lab includes a step‑by‑step algorithm, solution code, and expected output. 

Lab 1 – Reverse Order (Print Digits in Reverse Column)

Score: 0.1

Task: Write a program that reads a natural number and prints its digits in a column in reverse order.

📌 Algorithm

  1. Read the integer n.
  2. Set up a while loop that runs as long as n != 0.
  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.
  6. The loop repeats until n becomes 0.

💻 Solution Code


n = int(input())
while n != 0:
    print(n % 10)
    n = n // 10
                

📤 Expected Output

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. This ensures we process every digit, including the last one.
  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.

Lab 2 – All Together (Sum, Count, Product, Average, First, First+Last)

Score: 0.1

Task: Given a natural number, compute:

  • Sum of its digits
  • Number of digits
  • Product of its digits
  • Average of its digits (as a float)
  • Its first digit
  • Sum of its first and last digit

📌 Algorithm

  1. Initialize total = 0, count = 0, product = 1. Store original = n.
  2. Loop: extract digits, add to total, increment count, multiply to product, remove last digit.
  3. After the loop, compute:
    • first_digit = original // (10 ** (count - 1))
    • last_digit = original % 10
    • average = total / count
  4. Print all results.

💻 Solution Code


n = int(input())
original = n

total = 0
count = 0
product = 1

while n != 0:
    digit = n % 10
    total += digit
    count += 1
    product *= digit
    n //= 10

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)
                

📤 Expected Output

Input: 5678
Output:
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 to product, remove digit.
  3. After the loop, first_digit = original // (10 ** (count - 1)) (since count is the number of digits, 10^(count-1) gives the highest place value).
  4. last_digit = original % 10.
  5. Calculate average = total / count.
  6. Print all results.

Lab 3 – Identical Digits

Score: 0.1

Task: Determine if a number consists of identical digits (e.g., 111 → YES, 112 → NO).

📌 Algorithm

  1. Handle the n == 0 edge case (treat as YES).
  2. Store the last digit of the number 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 is_identical = False and break.
  5. Print the result based on the flag.

💻 Solution Code


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

📤 Expected Output

Input: 111111
Output: YES

Input: 111112
Output: NO
📖 Step‑by‑Step Explanation
  1. Handle the n == 0 edge case.
  2. Store the last digit of the number 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 is_identical = False and break out of the loop.
  5. Print the result based on the flag.

Lab 4 – Finding the Maximum and Minimum Digit

Score: 0.1

Task: Find the maximum and minimum digit of a given number.

📌 Algorithm

  1. Read the number n.
  2. Initialize max_digit and min_digit with the last digit of n.
  3. Remove the last digit from n.
  4. Loop while n != 0:
    • Extract the current last digit.
    • Update max_digit and min_digit if necessary.
    • Remove the last digit.
  5. Print the results.

💻 Solution Code


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)
                

📤 Expected Output

Input: 53258
Output:
Max digit: 8
Min digit: 2
📖 Step‑by‑Step Explanation
  1. Read the integer n.
  2. Initialize max_digit and min_digit with the last digit of n.
  3. Remove the last digit from n.
  4. While n != 0, extract the current last digit, compare with max_digit and min_digit, and update if necessary.
  5. After the loop, print the results.

✏️ Practice Exercises (Independent Work)

Try these on your own. Each practice includes a hint. Score: 0.5 each.

Introduction to while loop

Practice 1 – Countdown

Score: 0.2

Task: Write a program that reads n and prints all numbers from n down to 1 using a while loop.

Input: 5
Output:
5
4
3
2
1
📖 Algorithm
  1. Read n.
  2. While n > 0, print n and decrement n by 1.

Practice 2

Score: 0.2

Task: Output the sequence 15 16 17 18 19 20 ... 30 (from 15 to 30).

results:
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

Practice 3

Score: 0.2

Task: Output the sequence of integers: 20 18 16 ... 2 (from 20 downto 2).

20 18 16 14 ... 2

Practice 4

Score: 0.2

Task: Output the sequence of real numbers: 

0.1  0.3  0.5  0.7  0.9  1.1

Practice 5

Score: 0.3

Task: Two integers A and B are given (A < B). Output integers between A and B (including A and B themselves) in ascending order and output the number (quantity) of these numbers.

enter two numbers, please: A= , B = 
>>> -1  >>> 5
result:  
-1 0 1 2 3 4 5  quantity = 7

Practice 6

Score: 0.2

Task: 5 integers are entered. After entering each number, the program should print their sum.

enter 5 numbers:
>>> 4
entered number: 4  => sum = 4
>>> 7
entered number: 7 => sum = 11  
>>> 3
entered number: 3 => sum = 14 
>>> 2
entered number: 2 => sum = 16
>>> 6
entered number: 6 => sum = 20         
      

Practice 7

Score: 0.2

Task: 5 real numbers are entered. The program should output their sum only once, just before the end of the program.

enter 5 real numbers: 
>>> 4.2  >>> 7.1  >>> 3.1  >>> 2.5  >>> 8.6
sum = 25.5

Practice 8

Score: 0.2

Task: Calculate a product of 2-digit even integers in the interval [10;30] (10 * 12 * 14 * … * 28 * 30).

product = 165412864

Practice 9

Score: 0.3

Task: 10 randomized integers are given. You should use a while loop and variable named counter to find the quantity of positive among the numbers.

Note: You should use random function to have randomized sequence of numbers

1 6 10 10 -2 1 -4 4 -4 2 
numbers of positive:  7 

Practice 10

Score: 0.3

Task: 5 randomized integers are given. Output the maximum and minimum of entered numbers.

enter 5 integers:
>>> 5  >>> 3  >>> 8  >>> 1  >>> 2  
maximum is 8, minimum is 1

Sentinel Value

Practice 11 – Password Checker

Score: 0.5

Task: Write a program that keeps asking the user for a password until they enter the correct password ("python123"). Print "Access Granted" when correct.

Input: hello
Input: world
Input: python123
Output: Access Granted
📖 Algorithm
  1. Read a password.
  2. While password != "python123", read again.
  3. Print "Access Granted".

Practice 12 – Sum until Zero

Score: 0.5

Task: Write a program that reads integers from the user until 0 is entered, and then prints the sum of all numbers entered (excluding the 0).

Input: 5
Input: 10
Input: 3
Input: 0
Output: 18
📖 Algorithm
  1. Initialize total = 0.
  2. Read the first number.
  3. While the number is not 0, add it to total and read the next number.
  4. Print the total.

Practice 13

Score: 0.5

Task: The program receives a sequence of integers, each on a separate line. The sequence ends when any negative number appears. This terminating number is not included in the sequence. Write a program that outputs the sum of all members of the sequence.

Note: 0 is not an end marker and should be included in the sum. Use a while loop with the stopping condition. 
Input format
A sequence of integers, each on a separate line.
Output format
Print the sum of the sequence members.

1
2
3
4
5
6
7
8
9
10
-5
15
result: 55      
      

(Numbers from 1 to 10 are summed: 1+2+⋯+10=55. The number -5 stops the sequence and is not added. Numbers after it are ignored.)

Practice 14

Score: 0.5

Task: The program receives a sequence of integers representing student grades, each on a separate line. Valid grades are from 1 to 5. The sequence ends when any non‑positive number or any number greater than 5 appears. This terminating number is not part of the sequence. Write a program that outputs the count of grades equal to 5. Use a while loop with the stopping condition directly in the loop header (no while True or flags).
Input format
A sequence of integers, each on a separate line.
Output format
Print the number of fives in the sequence.

1
1
2
2
3
4
4
5
5
5
5
-17
1
2
5
4
result: 4

The four 5s before -17 are counted. The number -17 stops the sequence and is not processed; numbers after it are ignored.

Processing Digits of a Number

Practice 15 – Count of Even Digits

Score: 0.5

Task: Write a program that reads a number and counts how many of its digits are even.

Input: 1234
Output: 2

Input: 1357
Output: 0
📖 Algorithm
  1. Initialize count = 0.
  2. While n != 0, extract the last digit, check if it's even (digit % 2 == 0), increment count if true.
  3. Remove last digit.
  4. Print count.

Practice 16 – Contains Digit

Score: 0.5

Task: Write a program that reads a number and a digit, and checks if the digit exists in the number.

Input number: 4567
Input digit: 5
Output: YES
📖 Algorithm
  1. Read number n and target digit.
  2. Set found = False.
  3. While n != 0, extract digit, if equal to target, set found = True and break.
  4. Print "YES" if found else "NO".

Practice 17 – Second Digit from the Right

Score: 0.5

Task: Write a program that reads a natural number n (n > 9) and prints its second digit from the right.

Input: 4567
Output: 6

Input: 123
Output: 2
📖 Algorithm
  1. Read n.
  2. Remove the last digit: n //= 10.
  3. The new last digit is the second digit from the right: n % 10.
  4. Print it.

Practice 18 – Palindrome Check

Score: 0.5

Task: Write a program that reads a number and determines if it is a palindrome (reads the same forwards and backwards).

Input: 121
Output: YES

Input: 123
Output: NO
📖 Algorithm
  1. Read n, store original = n.
  2. Initialize reversed_n = 0.
  3. While n != 0, extract last digit, build reversed number: reversed_n = reversed_n * 10 + digit, remove digit.
  4. Compare original with reversed_n.

Practice 19 – Perfect Number Check (Simplified)

Score: 0.5

Task: Write a program that reads a number and calculates the sum and product of its digits. If sum == product, print "YES", otherwise "NO".

Input: 123
Output: YES

Input: 456
Output: NO
📖 Algorithm
  1. Initialize total = 0, product = 1.
  2. While n != 0, extract digit, add to total, multiply to product, remove digit.
  3. Compare total and product.

🔑 Answer Key – Practice Exercises

Solutions for the independent practice exercises. Check your work after attempting them.

Practice 1 – Solution


n = int(input())
while n > 0:
    print(n)
    n -= 1
            

Practice 2 – Solution


total = 0
n = int(input())
while n != 0:
    total += n
    n = int(input())
print(total)
            

Practice 3 – Solution


n = int(input())
count = 0
while n != 0:
    digit = n % 10
    if digit % 2 == 0:
        count += 1
    n //= 10
print(count)
            

Practice 4 – Solution


n = int(input("Enter number: "))
target = int(input("Enter digit: "))
found = False

while n != 0:
    digit = n % 10
    if digit == target:
        found = True
        break
    n //= 10

if found:
    print("YES")
else:
    print("NO")
            

Practice 5 – Solution


n = int(input())
n //= 10
second_digit = n % 10
print(second_digit)
            

Practice 6 – Solution


n = int(input())
original = n
reversed_n = 0

while n != 0:
    digit = n % 10
    reversed_n = reversed_n * 10 + digit
    n //= 10

if original == reversed_n:
    print("YES")
else:
    print("NO")
            

Practice 7 – Solution


n = int(input())
original = n
total = 0
product = 1

while n != 0:
    digit = n % 10
    total += digit
    product *= digit
    n //= 10

if total == product:
    print("YES")
else:
    print("NO")
            

Practice 8 – Solution


password = input()
while password != "python123":
    password = input()
print("Access Granted")
            

📋 Quick Reference – The while Loop & Digit Processing

Structure


# Initialization
variable = initial_value

# Condition check
while condition:
    # Body
    # ...
    # Update
    variable = new_value
                

Sentinel Pattern


value = input("Enter value: ")
while value != "stop":
    # Process value
    value = input("Enter next value: ")
                

Digit Processing Pattern


n = int(input())
while n != 0:
    digit = n % 10   # Extract digit
    # Process digit
    n //= 10         # Remove digit
                

Useful Math for Digits

  • n % 10 → last digit
  • n // 10 → removes last digit
  • n % 100 → last two digits
  • (n // 10) % 10 → second last digit

Preventing Infinite Loops:

  • 1. Initialize correctly.
  • 2. Update the loop variable inside the body.
  • 3. Ensure the condition will eventually become False.

© 2026 Python Module – The while Loop & Digit Processing  |  Keep iterating!

◄ Module 2.1 – The for Loop

Blocks

Skip Navigation

Navigation

  • Home

    • Site pages

      • My courses

      • Tags

    • My courses

    • Courses

      • Осенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

        • Этика ИИ

        • ОНС-Н_1

        • Прогр-ММ-2

        • Прогр-ММ-1

        • АБиМ-ИИБ26

        • МСиТВ_АБМ_2026

        • Python Eng

          • General

          • Module 1: Basics and Conditions

          • Module 2: LOOPs

            • AssignmentModule 2.1 – The for Loop

            • AssignmentModule 2.2 - The while Loop and Digit Processing

          • Module 3: Strings and Slices

          • Topic 3

          • Topic 4

          • Topic 5

          • Topic 6

          • Topic 7

          • Topic 8

          • Topic 9

          • Topic 10

        • Экзамен ИКТ

        • ТестИИ

        • Информатика-Осень-ПМИ-2

        • Информатика-осень-ПМИ-1

      • Весенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

      • Воскресная компьютерная школа

        • Пользователь компьютера плюс

        • Пользователь прикладных программ

        • Программирование I ступень

        • Программирование II ступень

        • Программирование III ступень

        • Архив

      • Воскресная математическая школа

        • Открытое тестирование РНОМЦ и мехмата ЮФУ

          • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2026

          • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2025

        • Олимпиадная математическая школа

        • Повышение квалификации

        • Доступная математика

        • Лаборатория математического онлайн-образования мех...

        • Осенняя универсиада

        • Научно-практическая конференция

        • ВМШ

          • ВМШ -2025

          • ВМШ - 2026

        • Летняя олимпиадная математическая школа РНОМЦ и ме...

      • Государственная итоговая аттестация

      • Дополнительное образование

      • Олимпиады

      • Видеолекции

      • Разное

      • Архив курсов

      • Заочная школа мехмата ЮФУ

Supplementary blocks

You are currently using guest access (Log in)
Python Eng
Data retention summary
Get the mobile app
Яндекс.Метрика