Search code examples
pythonstringloopsfor-loopnumbers

Count number of digits using for loop in Python


I want to count number of digits of any digits number without converting the number to string and also using for loop. Can someone suggest how to do this.

num = int(input("Enter any number : "))
temp = num
count = 0
for i in str(temp):
    temp = temp // 10
    count += 1
print(count)

Solution

  • You don't have to create a temp variable as num already contains the input.

    If there should only digits being entered, you can first check that with a pattern, then get the length of the string without using any loop.

    import re
    
    inp = input("Enter any number : ")
    m = re.match(r"\d+$", inp)
    
    if m:
        print(len(m.group()))
    else:
        print("There we not only digits in the input.")