Q. Python Program to Count the Number of Digits in a Number.


Here you will find an algorithm and program in Python programming language to count number of digits in a number. First let us understand this.

Explanation : Suppose an input number is given as 12341 then the output will be 5 as there are 5 digits in the given number and digits are 1, 2, 3, 4, 1.

Algorithm to count the number of digits in a given number

START
step 1 : Input a number from user. Store it in some variable say num.
step 2 : Initialize another variable to store total digits say digit = 0.
step 3 : while num != 0 then increment count by 1 i.e. count+=1.
step 4 : Divide num by 10 to remove last digit of the given number i.e. num = num / 10.
step 5 : Repeat step 3 to 4 till num != 0.
STOP


Python Program to Count Number of Digits in a Number

def count_digit(num): 
count = 0
while num != 0: 
	num //= 10
	count+= 1
return count

num = 874512369
print ("Number of digits : % d"%(count_digit(num))) 

Output

Number of digits : 9