Python Program to Count Digits in a Number
This article was created to cover some programs in Python that count the total number of digits in a given number. Here is a list of programs created for this article:
- Count digits in a number using the "while" loop.
- Count digits in a number using the "len()" function.
For example, if the user inputs a number like "4298", then the output will be "4" because the number contains 4 digits.
Count the total digits in a number using a while loop
The question is: write a Python program to count the total digits available in a given number using a 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:
Now supply the input "10324" as a number and press the ENTER key to count and print the total number of digits available in the given number, as shown in the snapshot given below:
Modified Version of the Previous Program
This program uses "end", which skips the insertion of an automatic newline. "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":
Count Digits using len()
This program uses a 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":
« Previous Program Next Program »
Liked this post? Share it!