Python Practice › Loop Programs › Program 19
Count the digits of a number
Write a Python program to count the digits of a number.
Input
908172
Output
Digits: 6
Approach
- Divide by 10 until the number becomes 0, counting the steps.
Solution
n = 908172count = 0while n > 0: n //= 10 count += 1print("Digits:", count)Output
Digits: 6
Line by line
Line 4
Each //= 10 removes one digit.
Tip
len(str(abs(n))) gives the same answer for non-zero numbers.
Learn the concept
New to this topic? Read the lesson, then come back.