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: 44587 â 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)) # 3Without 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)) # 1One 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
- An infinite loop from forgetting
n = n // 10â the condition never changes. - Handling zero wrongly: the loop never runs, so a bare while version returns 0 digits for the number 0.
- Counting the minus sign â
len(str(-320))is 4, not 3; takeabs()first. - Using
/(true division) instead of//â the number becomes a float and never reaches exactly 0. - Calling
len(n)on the number itself âlen()works on strings and containers, not ints, and raises a TypeError.
Practice on PyDebug
Turn the idea into a debugging habit with these free browser exercises: