Count Digits in a Number
Count how many digits an integer has using a loop.
BeginnerTopic: Loop Programs
Python Count Digits in a Number Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to count digits in a number
num = int(input("Enter an integer: "))
temp = abs(num)
if temp == 0:
count = 1
else:
count = 0
while temp > 0:
count += 1
temp //= 10
print("Number of digits in", num, "is", count)Output
Enter an integer: 12345 Number of digits in 12345 is 5
Understanding Count Digits in a Number
We repeatedly divide by 10 until the number becomes 0, counting how many times we can do this.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.