How to find the number of digits in a given number using Python?

PythonServer Side ProgrammingProgramming

In this program, we have to find the number of digits in an integer given by the user.

For example

User Input: 123, Output: 3

User Input: 1987, Output: 4

Algorithm

Step 1: Take Integer value as input value from the user

Step 2: Divide the number by 10 and convert the quotient into Integer type

Step 3: If quotient is not 0, update count of digit by 1

Step 4: If quotient is 0, stop the count

Step 5: STOP

Example Code

Live Demo

x = int(input("User Input: "))
count_of_digits = 0
while x > 0:
   x = int(x/10)
   count_of_digits += 1
print("Number of Digits: ",count_of_digits)

Output

User Input: 123
Number of Digits: 3

User Input: 1987
Number of Digits: 4

Explanation

When we divide a number by 10 and convert the result into type int, the unit's place digit gets deleted. So, by dividing the result each time by 10 will give us the number of digits in the integer. Once the result becomes 0, the program will exit the loop and we will get the number of digits in the integer.

raja
Published on 16-Mar-2021 14:03:11
Advertisements