Count Digits in a Number

Count how many digits an integer has using a loop.

PythonBeginner
Python
# Program to count digits in a number

num = int(input("Enter an integer: "))

temp = abs(num)

if temp == 0:
    count = 1
else:
    count = 0
    while temp > 0:
        count += 1
        temp //= 10

print("Number of digits in", num, "is", count)

Output

Enter an integer: 12345
Number of digits in 12345 is 5

We repeatedly divide by 10 until the number becomes 0, counting how many times we can do this.