Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

1 solution

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))
 
Share this answer
 
Comments
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)



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