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.
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:
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:
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:
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:
© Copyright 2021. All Rights Reserved.