Easy function, please help.
Michael Hrivnak
mhrivnak at hrivnak.org
Wed Feb 9 07:29:33 CET 2011
Your function only works if n is an integer. Example:
>>> num_digits(234)
3
>>> num_digits(23.4)
325
When doing integer division, python will throw away the remainder and
return an int. Using your example of n==44, 44/10 == 4 and 4/10 == 0
Before each iteration of the while loop, the given expression (in this
case just n) is evaluated as a boolean. Your function would act the
same if it looked like this:
def num_digits(n):
count = 0
while bool(n):
count = count + 1
n = n / 10
return count
0 of course evaluates to False as a boolean, which is why the while loop stops.
Just for kicks, this function would work about as well:
def num_digits(n):
return len(str(n))
And if either of these were a real function you planned to use, you'd
probably want to either cast n as an int ( int(n) ) or at least check
its type:
if not isinstance(n, int):
raise TypeError("WTF you didn't pass me an int")
Michael
On Wed, Feb 9, 2011 at 12:52 AM, Nanderson
<mandersonrandersonanderson at gmail.com> 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.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list