vendredi 27 août 2021

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

Aucun commentaire:

Enregistrer un commentaire