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