Easy function, please help.

Nanderson mandersonrandersonanderson at gmail.com
Wed Feb 9 06:52:28 CET 2011


def num_digits(n):
    count = 0
    while n:
        count = count + 1
        n = n / 10
    return count

This is a function that basically says how many digits are in a
number. For example,
>>>print num_digits(44)
2
>>>print num_digits(7654)
4

This function counts the number of decimal digits in a positive
integer expressed in decimal format. I get this function ALMOST
completely. The only thing I don't understand is why it eventually
exits the loop, and goes off to the second branch. "while n" is
confusing me. What I am thinking is that if someone puts "while n" the
loop would be infinite. I get what is happening in the function, and I
understand why this would work, but for some reason it's confusing me
as to how it is exiting the loop after a certain number of times. Help
is appreciated, thanks.



More information about the Python-list mailing list