← Back

Home › Python programs (Hindi)

Number के Digits गिनना Python में — code और dry run

Read this in English

Problem statement

एक पूरे number में कितने digits हैं गिनना। 4587 में 4 digits हैं, 0 में 1, और -320 में 3 (माइनस का चिह्न 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

4587 trace करें। n = 4587 > 0 → काटो → n = 458, count = 1। n = 458 → n = 45, count = 2। n = 45 → n = 4, count = 3। n = 4 → n = 0, count = 4। अब शर्त fail — loop रुका, जवाब 4। String version से cross-check: str(4587) = "4587", लंबाई 4। दोनों तरीकों का जवाब हमेशा same होना चाहिए — नहीं तो कोई bug है।

Common errors

Practice on PyDebug

Concept समझने के बाद इन free problems को browser में solve करें: