Python Program to Count Digits in Given Number

Problem: Write a python program to count the number of digits in given number.

Solution: This python program accepts a number from user. It uses while loop and modulo division to extract last of digit of given number and increments the counter. Then it divides the number by 10 and stores the integral part. This process continues until the division becomes zero and finally we get the cout of digits in given number.

Example:

number = 123
count = 0
Extract last digit and
increment the counter
last digit = 3
count = count + 1
Divide the number by 10
number = 12
Extract last digit and increment counter
last digit = 2
count = count + 1
Divide the number by 10
number = 1
Extract last digit
last digit = 1
increment the counter
count = count + 1
divide the number by 10
number = 0
Stop as number = 0
terminating condition met

Python program to count digits in a nunber

num=int(input("Enter any number: "))
count=0
while(num>0):
    count=count+1
    num=num//10
print("The number of digits in given number: ", count)

Output:

Enter any number: 4321
The number of digits in given number:  4