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 Get Current time
Python Program to Find Factorial of Number Using Recursion
Python Global, Local and Nonlocal variables
Python List sort()
Python list()
Python Program to Append to a File
Python tuple()
Python Dictionary update()
Python Program to Check If Two Strings are Anagram
Python Program to Shuffle Deck of Cards
Python String rpartition()
Python Set pop()
Python float()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python break and continue
Python Set symmetric_difference()
Python String rstrip()
Python Errors and Built-in Exceptions
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Debug a JavaMail Program
Python String startswith()
Python String format_map()
Python strptime()
Python Program to Get File Creation and Modification Date
Python frozenset()
Python String rjust()
Python next()
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Find the Factorial of a Number
Python Namespace and Scope
Python RegEx
Python String rsplit()