Count number of digits using for loop in Python

Viewed 60

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)
3 Answers
i = int(input('num : '))
j=0
while i:
    j+=1
    i//=10
print(j)

Repeats dividing the entered number stored in i by 10 and adds 1 to j (result) Checks From i if it finds it equal to 0 it exits the iteration and prints the result j

i = 103


j = 0

#inside repetition :

i//=10    #i=10


j+=1      #j=1


i!=0      #completion

i//=10    #i=1



j+=1      #j=2



i!=0      #completion

i//=10    #i=0



j+=1      #j=3



i==0      #break

print j #result

If you stick to using input, you can't get away the fact that this function prompts a String. As for the for loop, simply count the number of characters in the input string:

num = input("Enter any number : ")                                                                       
print(len(num))  

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.")
Related