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
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.

After this program

If the idea is still fuzzy, read Day 9: Loops and Iteration in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 loop programs, or see every topic on Python exercises.