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:
Python Program to Find the Factorial of a Number
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Exception Handling Using try, except and finally statement
Python Program to Capitalize the First Character of a String
Python bool()
Python String isalnum()
Python Decorators
Python Program to Find ASCII Value of Character
Python float()
Python Program to Find LCM
Python Program to Get the Last Element of the List
Python delattr()
Python tuple()
Python String find()
Python List
Python hex()
Python Program to Get the File Name From the File Path
Python Set symmetric_difference_update()
Python Program to Represent enum
Python Program to Print Output Without a Newline
Python List reverse()
Python String center()
Python Program to Delete an Element From a Dictionary
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Set clear()
Python Program to Access Index of a List Using for Loop
Python break and continue
Python *args and **kwargs
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python pass statement
Deep Learning with Python - Francois Chollet
Python Functions