Count Digits in a Number in Python

Count how many digits an integer has using a loop.

BeginnerLoop ProgramsExample 9 of 25
count-digits-in-a-number.py
Run in browser
1# Program to count digits in a number
2
3num = int(input("Enter an integer: "))
4
5temp = abs(num)
6
7if temp == 0:
8 count = 1
9else:
10 count = 0
11 while temp > 0:
12 count += 1
13 temp //= 10
14
15print("Number of digits in", num, "is", count)

Output

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

What's going on

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