Python Program to Count Digits in a Number

This article is created to cover some programs in Python, that counts total number of digits in a given number. Here are the list of programs created for this article:

For example, if user inputs a number say 4298, then the output will be 4 because the number contains 4 digits.

Count Total Digits in a Number using while Loop

The question is, write a Python program to count total digits available in a given number using while loop. The program given below is the answer to this question:

print("Enter the Number: ")
num = int(input())
tot = 0

while num:
  num = int(num/10)
  tot = tot+1

print("\nTotal Digit: ")
print(tot)

Here is its sample run:

python count digits in number

Now supply the input say 10324 as a number and press ENTER key to count and print the total number of digits available in the given number as shown in the snapshot given below:

count digits in number python

Modified Version of Previous Program

This program uses end, that skips insertion of an automatic newline. The str() converts any type of value to a string type.

print(end="Enter the Number: ")
num = int(input())
tot = 0

while num:
  num = int(num/10)
  tot = tot+1

if tot>1:
  print("\nThere are " +str(tot)+ " digits available in the number")
elif tot==1:
  print("\nIt is a single digit number")

Here is its sample run with user input, 12340:

python count number of digits in number

Count Digits using len()

This program uses predefined function named len() to count digits in a given number:

print(end="Enter the Number: ")
num = int(input())

num = str(num)
numLen = len(num)

print("\nTotal Digit: " + str(numLen))

Here is its sample run with user input, 401:

count number of digits in number python

Python Online Test


« Previous Program Next Program »