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 number23num = int(input("Enter an integer: "))45temp = abs(num)67if temp == 0:8 count = 19else:10 count = 011 while temp > 0:12 count += 113 temp //= 101415print("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.