Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting number of digits of input using python

I am trying to count the number of digits of an input. However, whenever I input 10 or 11 or any two digit number, the output is 325. Why doesn't it work?

inputnumber = int(input())
countnumber = inputnumber
digitcount = 0
while countnumber > 0:
    digitcount += 1
    countnumber = countnumber/10

print(digitcount) 
# result is 325 when input is 10 or 11
like image 727
Naya Keto Avatar asked Dec 17 '22 23:12

Naya Keto


1 Answers

Your error mainly happened here:

countnumber=countnumber/10

Note that you are intending to do integer division. Single-slash division in Python 3 is always "float" or "real" division, which yields a float value and a decimal part if necessary.

Replace it with double-slash division, which is integer division: countnumber = countnumber // 10. Each time integer division is performed in this case, the rightmost digit is cut.

You also have to watch out if your input is 0. The number 0 is considered to be one digit, not zero.

like image 105
Ṃųỻịgǻňạcểơửṩ Avatar answered Feb 03 '23 04:02

Ṃųỻịgǻňạcểơửṩ