DEV Community

Cover image for Python Problem Solving: Working with Numbers and Digits
Megalraja
Megalraja

Posted on

Python Problem Solving: Working with Numbers and Digits

Let's solve a simple Python problem using a while loop.

1. Can we count the number of digits in a given number?

Example:

num = 12345
Enter fullscreen mode Exit fullscreen mode

Solution:

First, introduce a variable called count and initialize it to 0.

num = 12345
count = 0  # Initial value is zero

while num != 0:
    num = num // 10  # Removes the last digit
    count += 1

print("Number of digits:", count)
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • num = num // 10 removes the last digit from the number.
  • count += 1 increases the count by 1.
  • The loop continues until the number becomes 0.

Output:

Number of digits: 5
Enter fullscreen mode Exit fullscreen mode

That's it! We counted the total number of digits using a simple while loop without using any built-in functions.

2. Can we solve the Sum of Digits?

Now, let's solve another problem using the same number.

Problem: Find the sum of all digits in a given number.

For example:

number = 12345
Enter fullscreen mode Exit fullscreen mode

Expected output:

Sum of digits: 15
Enter fullscreen mode Exit fullscreen mode

Step 1: Initialize a variable

Introduce a variable sum_of_digit to store the total sum.

sum_of_digit = 0
Enter fullscreen mode Exit fullscreen mode

Step 2: Get the last digit

We already know that the modulus operator (%) returns the remainder.

When we use % 10, we get the last digit of the number.

12345 % 10  # 5
Enter fullscreen mode Exit fullscreen mode

Step 3: Implement the logic

We can use the same while loop concept from the previous problem.

number = 12345
sum_of_digit = 0

while number != 0:
    sum_of_digit += number % 10
    number = number // 10

print("Sum of digits:", sum_of_digit)
Enter fullscreen mode Exit fullscreen mode

How does the logic work?

  • number % 10 extracts the last digit.
  • sum_of_digit += number % 10 adds the extracted digit to the total.
  • number // 10 removes the last digit.

This process continues until the number becomes 0.

Output:

Sum of digits: 15
Enter fullscreen mode Exit fullscreen mode

Key Takeaway

We used two operators to solve this problem:

  • % 10 – Extracts the last digit.
  • // 10 – Removes the last digit.

These two operations are useful for solving many number-based problems in Python.

Top comments (0)