Im trying to write a function which counts the number of digits in a number - with no string operation. here is my code:
def count_digits(n): count_list=[] while (n>0): n=n%10 i=n count_list.append(i) n=n/10 return len(count_list) n=12345 print count_digits(n) By using % i get the last digits - in order to add it to a list. By using / i throw the digit from the number.
The script does not work. For each n i put, the script just prints 1.
Thanks!
returnstatement is not properly indented. It should be outside thewhileloop.count_listwhen you could just use an incrementing counter seems kind of silly (only trick is that you handle0specially, or use a somewhat kludgy Python equivalent ofdo/whileto avoid the need to handle it specially).import math, you can get the number of digits usingint(math.log10(n)) + 1