Python Program to Calculate Number of Digits in an Integer

By | May 14, 2018

Ques – Accept an integer value from the user and calculate the number of digits in provided value. e.g. 679 has 3 digits

Calculate the number of Digits in an Integer using Python

number = int(input('Enter a number '))
length = 0

while number/10 >= 1:
	number //= 10


print('There are {} number of digits in the provided integer.'.format(length))


Explanation of Program to calculate the number of Digits in Python

  • In the first line, we are using input() function and accepting the input from the user. After that, we are type casting it to an integer value.
  • In the second line, we are declaring an integer variable length and set its value to 0. We will use this variable to store the final output of our answer.
  • In the fourth line, we are using the while loop in our program. This loop will iterate until the original integer is greater than or equal to 1.
  • In the fifth line, we are using floor division operator to reduce the value by 10.
  • In the sixth line, we are incrementing the length.
  • In the eighth line, we are incrementing the length again, because if we passed single digit integer, then it will never go to the while loop. So in that case, we have to increment the length variable here too.
  • In the last line, we are printing the output on the console.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.