Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #55726
| References | <8e0efff7-4d38-4a85-9653-2178388603d4@y36g2000pra.googlegroups.com> |
|---|---|
| Date | 2011-02-09 01:29 -0500 |
| Subject | Re: Easy function, please help. |
| From | Michael Hrivnak <mhrivnak@hrivnak.org> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.29.1297232975.1633.python-list@python.org> (permalink) |
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@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
>
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: Easy function, please help. Michael Hrivnak <mhrivnak@hrivnak.org> - 2011-02-09 01:29 -0500 Re: Easy function, please help. Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-02-10 07:08 +0000 Re: Easy function, please help. drygal <drygalski@googlemail.com> - 2011-02-09 22:53 -0800
csiph-web