Table of Contents
In this example, you will learn to count the number of digits present in a number.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Count Number of Digits in an Integer using while loop
num = 3452
count = 0
while num != 0:
num //= 10
count += 1
print("Number of digits: " + str(count))
Output
Number of digits: 4
In this program, the while loop is iterated until the test expression num != 0 is evaluated to 0 (false).
- After the first iteration,
numwill be divided by 10 and its value will be 345. Then, thecountis incremented to 1. - After the second iteration, the value of
numwill be 34 and thecountis incremented to 2. - After the third iteration, the value of
numwill be 3 and thecountis incremented to 3. - After the fourth iteration, the value of
numwill be 0 and thecountis incremented to 4. - Then the test expression is evaluated to false and the loop terminates.
2. Example 2: Using inbuilt methods
num = 123456 print(len(str(num)))
Output
6
In the above example, we first convert the integer value into string by using str(). Then, we find the length of the string using len().
Related posts:
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Check If a String Is a Number (Float)
Python Program to Differentiate Between del, remove, and pop on a List
Python String isidentifier()
Python Get Current time
Python Dictionary
Python Program to Delete an Element From a Dictionary
Python timestamp to datetime and vice-versa
Python Dictionary fromkeys()
Python Set discard()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python String maketrans()
Python String strip()
Python Program to Copy a File
Python Machine Learning - Sebastian Raschka
Python divmod()
Python Dictionary get()
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Program to Create a Long Multiline String
Python tuple()
Python Dictionary update()
Python String isdecimal()
Python String upper()
Python Variables, Constants and Literals
Python *args and **kwargs
Python Set update()
Python Program to Swap Two Variables
Python Dictionary items()
Python pass statement
Python String rstrip()
Python Program to Get the Full Path of the Current Working Directory
Python Program to Multiply Two Matrices