← Back

Home â€ē Python programs

Count Digits of a Number in Python

⤇⤏āĨ‡ Hindi ā¤ŽāĨ‡ā¤‚ ā¤Ēā¤ĸā¤ŧāĨ‡ā¤‚

Problem statement

Count how many digits a whole number has. 4587 has 4 digits, 0 has 1 digit, and -320 has 3 digits (the minus sign is not a digit).

Approach 1: simple loop

Strip the number down with integer division: every // 10 removes one digit from the right, so count how many chops it takes to reach 0.

n = 4587
count = 0

while n > 0:
    n = n // 10
    count = count + 1

print(count)
# Output: 4

4587 → 458 → 45 → 4 → 0: four chops, four digits. The loop body must update n, or it will run forever.

Approach 2: reusable function

Make it a function and defend the two edge cases up front: zero (one digit) and negatives (drop the sign before counting).

def count_digits(n):
    if n == 0:
        return 1
    n = abs(n)               # -320 becomes 320
    count = 0
    while n > 0:
        n //= 10
        count += 1
    return count

print(count_digits(4587))   # 4
print(count_digits(0))       # 1
print(count_digits(-320))    # 3

Without the zero case, the while loop never runs and the function would wrongly return 0 — the classic edge-case trap of this program.

Approach 3: Pythonic alternative

Python can also answer by reading the number as text: convert to a string and measure its length, after taking abs() to drop the minus sign.

def count_digits(n):
    return len(str(abs(n)))

print(count_digits(4587))   # 4
print(count_digits(-320))   # 3
print(count_digits(0))      # 1

One line, all three edge cases handled by the same trick — str(abs(0)) is "0", whose length is 1. For an interview, know the division method; for working code, this is the honest, readable choice.

Dry run

Trace 4587. Check: n = 4587 > 0 → chop → n = 458, count = 1. n = 458 > 0 → n = 45, count = 2. n = 45 > 0 → n = 4, count = 3. n = 4 > 0 → n = 0, count = 4. Now n = 0 fails the condition — loop stops, answer 4. Cross-check with the string version: str(4587) is "4587", and its length is 4. Both methods must always agree.

Common errors

Practice on PyDebug

Turn the idea into a debugging habit with these free browser exercises: