Python program to count the Digits

In the previous article we wrote a program to print Pyramid patterns in Python, now let us look at a program to count the number of digits present in a program. The program should be written in such a way as to accept numeric input values from the user which are greater than 0, the program than returns a count of how many individual digits at each position is present in the number.

Writing a Python program to count the Digits

In simple mathematical logic, the way to obtain the number of digits would be through the use of division operator. For example with the number 9253:

x = 9253
x = x//10 = 925
x = x//10 = 92
x = x//10 = 9
x = x//10 = 0
x = int(input("Enter x:"))
res = 0
while x > 0:
    x =x//10
print("Count of Digits is: ", res)

Output:
Enter x:890
Count of Digits is: 3

If we look at this program logic in depth of each iteration of the loop by tracing it manually it would look something like this:

Program tracing:

Base values
Enter x: 9542(Input)
res=0(initialized value)

After 1st Iteration:
x = 954
res = 1
After 2nd Iteration:
x=95
res = 2
After the 3rd Iteration:
x=9
res = 3
After 4th Iteration:
x=0
res = 4

Each time a digit is taken off the input number the count of res is increased by 1, once the entered number reaches zero the final count of the number of total digits is obtained. Thus, we have seen the program and implementation for obtaining the count of digits. In the next article, we will explore Factorial program in Python.

Leave a Comment