Python Program to Count the Number of Digits in a Number
Beginner · Numbers
This program counts how many digits a whole number has, for example 7 digits in 9045812. It divides the number by 10 again and again, since each division removes one digit.
Program
count_digits.py
num = 9045812 # or: num = int(input("Enter a number: "))
n = abs(num) # ignore a minus sign
count = 0
while n > 0:
n //= 10 # drop the last digit
count += 1
if num == 0:
count = 1 # 0 still has one digit
print(f"Number of digits in {num}: {count}")
Output
Number of digits in 9045812: 7
How it works
abs()removes a minus sign, so -305 is counted like 305.n //= 10is whole-number division by 10, which drops the last digit: 9045812 becomes 904581.- Each pass of the loop adds 1 to
count, and the loop stops when no digits are left. - For 0 the loop never runs, so it is set to one digit separately.
Other ways to write it
Using len() and str()
Using len() and str()
for num in [9045812, 7, 0, -305]:
digits = len(str(abs(num)))
print(f"{num} has {digits} digit(s)")
Output
9045812 has 7 digit(s) 7 has 1 digit(s) 0 has 1 digit(s) -305 has 3 digit(s)
Turning the number into text and counting its characters is the shortest way, and abs() stops the minus sign being counted.
Using a logarithm
Using a logarithm
import math
num = 9045812
count = math.floor(math.log10(num)) + 1
print(f"Number of digits in {num}: {count}")
Output
Number of digits in 9045812: 7
math.log10() tells you which power of 10 the number is, so its whole part plus 1 is the digit count. It only works for positive numbers.
Try it yourself
Change the loop so it also adds up the digits while it counts them.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises