简体   繁体   中英

Python digit counter function doesnt work properly

When I try to make a function that counts the digits in a number, it doesn't work properly, it doesn't show the number of digits,but some random numbers

def count(number):
counter=0
while number>0:
    number/=10
    counter+=1
return counter

can you please tell me what I'm doing wrong?

If we explore what your function is doing, it is just continuously dividing an input number by 10. In math, if you keep dividing a real number not equal to zero (I don't want to get into imaginary numbers) by another larger real number not equal to zero, the result will never equal zero - you will have an infinite list of numbers decreasing in size, getting infinitesimally small.

For example if our number is 10, your function function will set number to:

10
1
.1
.01
.001
.0001
.00001
...

In programming (specifically python), this will continue until the float value is too small for python to differentiate from 0.0, and will return a "random" number.

Another way to accomplish what you are trying to do would be to convert the number to a string and get the length of the string.

def count(number):
    counter = str(number)
return len(counter)

You can also use "floor division", which rounds the result of your division down to the nearest whole integer, if you want to keep your function in a purely mathematical domain.

def count(number):
    counter=0
    while number>0:
        number //= 10
        counter += 1
    return counter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM