0
def digits(n):
    count = 0
    if n == 0:
      digits = int(n)+1
    while (n > 0 ):
        count += 1
        n = n // 10
    return count

print(digits(25))  # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0))   # Should print 1
def digits(n):
count = 0
if n == 0:
  ___
while (___):
    count += 1
    ___
return count

print(digits(25))  # Should print 2
print(digits(144)) #Should print 3
print(digits(1000)) # Should print 4
print(digits(0))   # Should print 1

Here's the Question: Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits. What am I missing? It returns 2 3 4 0

Kevin
  • 33
  • 2
  • 2
  • 3
  • It should be `count = int(n)+1` or just `return int(n)+1`. You also don't need to cast to `int`. – Guy Jan 27 '20 at 19:05

1 Answers1

7

For case when n is equal to 0 you just need to return 1.

def digits(n):
   count = 0
   if n == 0:
      return 1
   while (n > 0):
      count += 1
      n = n//10
   return count

For an easiest solution, you could use str constructor with len.

def digits(n):
   return len(str(n))

print(digits(25))
print(digits(144))
print(digits(1000))
print(digits(0))

Output

2
3
4
1
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128