ComputerShikshak.com

Python - Count Number of Digits of a Number

Problem Statement

Write a program in Python to count the number of digits present in an integer number entered by the user.

Brief Description

According to the problem statement we have to write a program in Python that will take an integer value as input from the user through the keyboard and will count the total number of digits present in that number.

For example, if the user enters 132 as input, the program will generate 3 as output since the number 132 contains 3 digits.

Program

				
					num=int(input("Enter a number: "))
count=0
temp=abs(num)
while True:
    count=count+1    #OR count+=1
    temp=temp//10    #OR temp//=10
    if temp==0:
        break
print("Number of digits present in",num,"is",count)
				
			

Output

Explanation

In this program:
  • 3 variables namely num, temp and count are used.
  • The integer value entered by the user is stored in num.
  • Initially 0 is stored in count.
  • The absolute value corresponding to the value stored in num is stored in temp.
The step-by-step working of the while loop (when num and temp both contains 132) is shown in the table given below:
numcount=count+1;counttemp=temp//10;temptemp==0Comment
132-----0-----132Initial Values
132count=0+1;1temp=132/10;1313==0
↓
False
Iteration 1
132count=1+1;2temp=13/10;11==0
↓
False
Iteration 2
132count=2+1;3temp=1/10;00==0
↓
True
Iteration 3
[control
goes
outside
while
loop
as
temp==0
is
evaluated
to
True]
While executing the while loop:
  • At first the value stored in count is incremented by 1
  • After that the value stored in temp is divided by 10 to remove the last digit from the value stored in it and the result is stored in the same variable i.e. temp.
  • At the end of each iteration value of temp is checked to see whether it has become 0 or not.
  • The condition temp==0 will produce either True or False after evaluation.
    • If it is True then the “break;” statement is executed and the control goes to the statement written immediately after the loop.
    • If it is False then the statements written within while loop are executed again and the loop continues to iterate till the condition is False.

Thus the above process is used to count the total number of digits present in the given number.

The final result is stored in count. 

Finally the number of digits present in the entered integer value along with the value is displayed on the output screen.

Share this page on
Scroll to Top