Written by Sai Sameera Thota on February 28, 2013 in Programming > Python

Python Program to get Number of Digits in a Number

GET ALERTS:

Get our Latest updates delivered to your mailbox!

So this is our first program of Python. This article explains how to get the Digit Count of a given Number using Python. Lets get started..
1. First of all Define a function count which takes number as input.
2. Convert the number into a string using the inbuilt function str and assign it to a new string variable n.
3. Define a new variable count.
4. for loop in python iterates over a string or a list

Ex:

for i in 'python':

print(i)

The output for the above program is
p

y

t

h

o

n

So, getting back to our program if we say:

for e in n:

It means that the variable ‘e’ iterates over the string n.For every iteration, the value of count increments by 1
and finally the value of count is returned and printed as the number of digits in a given number.

Python Program to get Number of Digits in a Number

#python program to find the number of digits in a given number 
def count(num):
    n = str(num)
    count = 0
    for e in n:
        count = count + 1
    print("Number of digits in the given number "+n)
    return count

print(count(1234))

Output:
python_digit_count

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: