In python, integer data type is used to represent positive and negative integers. In this article, we will discuss a program to count digits of an integer in python.
How to Count Digits of an Integer in Python?
To count the digits of a number, we will use an approach that divides the number by 10. When we divide an integer by 10, the resultant number gets reduced by one digit.
For instance, if we divide 1234 by 10, the result will be 123. Here, 1234 has 4 digits whereas 123 has only three digits. Similarly, when we divide 123 by 10, it will get reduced to a number with only 2 digits and so on. Finally the number will become 0.
You can observe that we can divide 1234 by 10 only 4 times before it becomes 0. In other words, if there are n digits in an integer, we can divide the integer by 10 only n times till it becomes 0.
Program to Count Digits of an Integer in Python
As discussed above, we will use the following approach to count digits of a number in python.
- First we will declare a value count and initialize it to 0.
- Then, we will use a while loop to divide the given number by 10 repeatedly.
- Inside the while loop, we will increment count by one each time we divide the number by 10.
- Once the number becomes 0, we will exit from the while loop.
- After executing the while loop, we will have the count of the digits of the integer in the count variable.
We can implement the above approach to count the number of digits of a number in python as follows.
number = 12345
print("The given number is:", number)
count = 0
while number > 0:
number = number // 10
count = count + 1
print("The number of digits is:", count)
Output:
The given number is: 12345
The number of digits is: 5
Conclusion
In this article, we have discussed an approach to count digits of an integer in python. To know more about numbers in python,you can read this article on decimal numbers in python. You might also like this article on complex numbers in python.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.