codingstreets
Search
Close this search box.

Python Program: Counting the Number of Digits

python-program-counting-the-number-of-digits
Photo by Vlad Bagacian on Pexels.com

In this article, we will explore different approaches to writing a Python program to count the number of digits in a given number and choose the most suitable one based on its simplicity, efficiency, and readability.

Table of Contents

Introduction

Counting the number of digits in a number is a common task in programming, and Python provides powerful tools to accomplish this efficiently. Counting digits is helpful in various scenarios, such as verifying the length of user-inputted numbers, processing large datasets, or solving mathematical problems that involve manipulating individual digits.

Whether you are a beginner or an experienced Python programmer, mastering this fundamental skill will equip you to handle numeric data effectively and efficiently in your Python projects. So let’s dive in and explore the world of counting digits in Python!

Using len function

Example: Use the built-in function len to count the number of digits.

				
					number = 12345
print(len(str(number)))

#output: 5
				
			

Explanation: 

len – Calculate the length of the string.

str – Converts the int class to the str class.

Since int has no attribute len, we first converted the number variable’s type from int to str by using the str class so that len can count the number of characters (digits) as the String character.

The code converts the number into a string, measures the string’s length (equivalent to the number of digits), and prints the result.

Using for loop

Example: Use for loop to count the number of digits.

				
					num = 1234567890
count = 0

for x in str(num):
    count = count + 1
print(count)

#output: 10 

				
			

Explanation: 

We first converted the num variable’s type from int to str by using the str class to treat it as a sequence of characters. 

In the next step, inside the loop, for each character x in the string, we increment the count value by 1. This means that for every iteration of the loop, we encounter one digit and keep track of the count. 

Finally, the loop finishes executing; we print the final value of the count, which represents the total number of digits in the given number.

Using range function

Example: Use the built-in function range to provide the number of digits.

				
					count = 0
for number in range(1, 11):
    count = count + 1
print(count)

#output:
10
				
			

Explanation:

We started with the for loop, which is used to iterate through a range of numbers from 1 to 10 (inclusive). The range() function generates a sequence of numbers based on the given start and end values. 

For each digit in a number, we increment the value of the count by 1. This means that for every iteration of the loop, we encounter one digit and keep track of the count. 

Finally, the loop finishes executing; we print the final value of the count, which represents the total number of digits in the given range of numbers.

Using while keyword 

Example: Use the while keyword to set the condition to find the number of digits.

				
					num = 1234567890
count = 0

while num != 0:
    num = num // 10
    count = count + 1
print(count)

#output:
10
				
			

Explanation:

We started with the while loop used to repeatedly execute the code block as long as num is not equal to 0. 

We divided num by 10 inside the loop using the floor division operator //. Later, we increment the value of the count by 1 for each iteration of the loop. This allows us to keep track of the count of removed digits.

Finally, when the loop has removed all digits, meaning it has iterated through each digit, the loop stops at the final value of count, representing the total number of digits present in the original number.

Using def function with for loop

Example: Use the def function to count the number of digits.

				
					def num(number):
    count = 0
    for x in str(number):
        count = count + 1
    print(count)

num(1234567890)

#output:
10
				
			

Explanation: 

We first define a function num that takes a parameter number representing the input number for which we want to count the digits. 

In the next step, we converted the num variable’s type from int to str by using the str class to treat it as a sequence of characters. 

Later, inside the loop, for each character x in the string, we increment the value of the count by 1. This means that for every iteration of the loop, we encounter one digit and keep track of the count. 

After the loop finishes executing, the final value of the count is printed using the print statement.

Finally, the loop finishes executing; we print the final value of the count, which represents the total number of digits in the given range of numbers.

Using def function with while loop

Example: Use the def function to count the number of digits.

				
					def count_digits(n):
    count = 0
    while n != 0:
        n = n // 10
        count += 1
    return count


n = int(input("Enter an integer: "))
print(count_digits(n))
				
			

Explanation:

The count_digits function initializes a variable called count to 0 that keeps track of the number of digits in the integer.

Now code enters the loop with the condition n != 0. The loop will be continued until n becomes 0, which means all digits have been counted.

Inside the loop, the code divides n by 10 using the floor division operator //. This process removes the last digit from n. For example, if n is 1234, n // 10 would be 123. And count variable is incremented by 1, indicating that a digit has been counted.

The loop continues as long as n is not equal to 0. When all the digits are removed from n and it becomes 0, the loop condition n != 0 evaluates to false, and the loop terminates.

Now, the function returns the current value of n which is the total number of digits.

Outside the function, the user is asked to enter the number using input() function and stored in variable n.The function count_digits is called with the user-inputted value of n and displayed result using print() function.

Conclusion

In this article, we have learned how to write a Python program that efficiently counts the number of digits in a given number. Later provided step-by-step explanations and code examples to guide you through the program and, finally, helped you to gain valuable insights into Python programming techniques and problem-solving strategies.

Recent Articles