Skip to content
Advertisement

Function digits(n) that returns how many digits the number has , returns a random value in python

The function digits, in the while loop – while (n > 0) returns 325 326 327 and 1 as the count value and if I use while (n > 1) it returns the correct number count. Any logical reason for this behavior?

def digits(n):
    count = 0
    if n == 0:
      return 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

Advertisement

Answer

There is a difference between / and //.

/ does the normal division given an accurate answer upto 15 decimal places in python. However, // is the floor division method where only the quotient of the division is returned.

try to replace:

n = n / 10

with this:

n = n // 10
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement