Counting number of digits of input using python

前端 未结 5 771
离开以前
离开以前 2021-01-19 18:46

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.

相关标签:
5条回答
  • 2021-01-19 18:55
    num = int(input())
    count = 0
    while num > 0:
      count += 1
      num = num // 10
    print(count)
    
    0 讨论(0)
  • 2021-01-19 18:57

    You must be using Python3, logically your function is right. You just have to change

    countnumber = countnumber // 10

    because Python3, // is floor division, meanwhile / is true division.

    >>>print(1 / 10)
    0.1
    >>>print(1 // 10)
    0
    

    Btw, as @chrisz said above, you can just simply using the len() function to get the number of digits of the input

    >>>print(len(input())
    
    0 讨论(0)
  • 2021-01-19 19:09

    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.

    0 讨论(0)
  • 2021-01-19 19:09

    I would not convert that beautiful input to int to be honest.

    print(len(input())
    

    would be sufficient.

    An easily understandable one liner that no one can complain about.

    • But of course, if negative sign bothers you like wisty said,

      len(str(abs(int (v))))
      

      will be safer for sure.

    • Again, if you are worried about the non numeric inputs like mulliganaceous said, you better cover that case.

      str = input()
      if str.isnumeric():
          print(len(str(abs(v))))
      else:
          print("bad input")
      
    0 讨论(0)
  • 2021-01-19 19:21

    The reason is that in python 3 the division of two integers yields a floating point number. It can be fixed using the // operator:

    number = int(input())
    digits_count = 0
    while number > 0:
        digits_count += 1
        number = number // 10
    
    0 讨论(0)
提交回复
热议问题