Easy function, please help.

Westley Martínez anikom15 at gmail.com
Thu Feb 10 23:36:01 EST 2011

On Tue, 2011-02-08 at 21:52 -0800, Nanderson wrote:

> 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.

I've become a little annoyed by this thread. Here's a good function that
does what you want:
def num_digits(n):
    """Return number of digits in an iteger."""
    count = 1
    while n:
        n = n // 10
        count += 1
    return count
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110210/5dedcc22/attachment.html>

More information about the Python-list mailing list