0

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)
Hari PN
  • 21
  • 1
  • 6
  • 3
    The number of digits is simply `len(str(temp))`, you don't need to actually iterate `str(temp)` in order to count the number of digits in it. –  Sep 16 '22 at 18:19
  • Does this answer your question? [How to find length of digits in an integer?](https://stackoverflow.com/questions/2189800/how-to-find-length-of-digits-in-an-integer) (There are 30+ answers on that question, some of which don't convert to string and also don't use loops. There doesn't need to be a separate question.) – Gino Mempin Sep 18 '22 at 01:58

3 Answers3

0

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))  
JustLearning
  • 1,435
  • 1
  • 1
  • 9
0

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.")
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

hope this helps , though this only works for whole numbers int type i.e non-decimal point valued

import math as m
n:int=int(input())
print(int(m.log10(m))+1)
  • 1
    The code snippet is rather dense and there are no explanations provided. It would be helpful if you could explain what you are doing with a little bit more text. – scr Jun 13 '23 at 06:39