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:
Node.js vs Python for Backend Development
Python Program to Shuffle Deck of Cards
Python Dictionary clear()
Python for Loop
Python String find()
Python Program to Make a Flattened List from Nested List
Python frozenset()
Python String upper()
Python input()
Python Statement, Indentation and Comments
How to get current date and time in Python?
Python Program to Find the Largest Among Three Numbers
Python Program to Safely Create a Nested Directory
Python Program to Reverse a Number
Python Custom Exceptions
Python Program to Find LCM
Python Keywords and Identifiers
Python Program to Get the Last Element of the List
Python Program to Concatenate Two Lists
Python eval()
Deep Learning in Python - LazyProgrammer
Python String islower()
Python hash()
Python locals()
Python Global, Local and Nonlocal variables
Python Program to Find the Sum of Natural Numbers
Python String endswith()
Python Numbers, Type Conversion and Mathematics
Python Program to Display Fibonacci Sequence Using Recursion
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Parse a String to a Float or Int