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,
num
will be divided by 10 and its value will be 345. Then, thecount
is incremented to 1. - After the second iteration, the value of
num
will be 34 and thecount
is incremented to 2. - After the third iteration, the value of
num
will be 3 and thecount
is incremented to 3. - After the fourth iteration, the value of
num
will be 0 and thecount
is 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 reversed()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python String isspace()
Python issubclass()
How to get current date and time in Python?
Deep Learning with Python - Francois Chollet
Python Program to Remove Duplicate Element From a List
Python Program to Find the Square Root
Python len()
Python Program to Get a Substring of a String
Python complex()
Python help()
Python list()
Python all()
Python List remove()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python String replace()
Python List clear()
Python Data Structures and Algorithms - Benjamin Baka
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Check if a Number is Odd or Even
Python Program to Remove Punctuations From a String
Python Program to Display the multiplication Table
Python strftime()
Python int()
Python Program to Convert Kilometers to Miles
Python Deep Learning Cookbook - Indra den Bakker
Python iter()
Python RegEx
Python List count()
Python Directory and Files Management