Menu
MENU
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:
num | count=count+1; | count | temp=temp//10; | temp | temp==0 | Comment |
---|---|---|---|---|---|---|
132 | ----- | 0 | ----- | 132 | Initial Values | |
132 | count=0+1; | 1 | temp=132/10; | 13 | 13==0 ↓ False | Iteration 1 |
132 | count=1+1; | 2 | temp=13/10; | 1 | 1==0 ↓ False | Iteration 2 |
132 | count=2+1; | 3 | temp=1/10; | 0 | 0==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