15,663,341 members
See more:
Quick python question if someone could help.

Below is a python function to count the number of digits. The function works except for one integer, 0.

How can I change this function so it also works for 0

Any feedback would be appreciated

Thank you

```def counter(num):
count = 0
while num != 0:
count = count+1
num = num//10
return count

counter(0)```

What I have tried:

I dont know how else to address this problem
Posted
Updated 14-Oct-22 4:06am

## Solution 1

Do a zero check before you enter the loop: if it's zero, return one immediately.

Alternatively, use logarithms to get the digits count:
Python
```import math
def counter(num):
if (num == 0):
return 1
return int(math.log10(num)) + 1
print(counter(0))
print(counter(1))
print(counter(12))
print(counter(123))
print(counter(1234))
print(counter(12345))
print(counter(123456))
print(counter(1234567))```

Ammar Basheer 14-Oct-22 14:11pm
Thank you!
OriginalGriff 14-Oct-22 15:01pm
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 steveb 75 OriginalGriff 60 Graeme_Grant 50 Andre Oosthuizen 30 Rick York 10
 OriginalGriff 2,203 Graeme_Grant 1,041 Richard Deeming 728 Richard MacCutchan 648 Dave Kreskowiak 473

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900