On Feb 8, 10:29 pm, Michael Hrivnak <mhriv...@hrivnak.org> wrote: > 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 > > > > > > > > <mandersonrandersonander...@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
Ah, thank you very much! I forgot completely about how python does division, do this confused me quite a bit. Thanks for the help, and the only reason I wrote the function this way is because I'm learning to program, and I'm try to do the exercises of the tutorial I'm reading. It really is for learning purposes. Thanks again! -- http://mail.python.org/mailman/listinfo/python-list