Find the number of digits in a number in Python
Hello coders!! In this section, we will learn how to find the number of digits in a number in a Python program.
Here, we will discuss two methods to implement this program:
- Iterative Method
- Recursive Method
Find the number of digits in a number in Python using Iterative Method
Let’s discuss the algorithm of this program for a better understanding of the working of this program.
Step1: Create a variable num that will store the integer given by the user and a flag variable count that will keep track of the number of iteration.
Step2: Define a while loop with a condition num!=0 so that it will iterate until the test expression is evaluated to false.
Step3: Inside of the while loop, divide the num in each iteration and increment the flag variable count by 1 until the num is reduced to 0.
Step4: Lastly, print the count that will give us the number of digits of that given number.
def count_digit(num): count = 0 while num != 0: num //= 10 count += 1 return count num = int(input("Enter a number to count: ")) print("Number of digits : % d" % (count_digit(num)))
Enter the number to count: 8764 Number of digits : 4
Enter the number to count: 95175385462 Number of digits : 11
Find the number of digits in a number in Python using Recursive Method
Here we are doing the same program using recursion. (a technique using a function that calls itself until a specified condition is met)
def count_digit(num): if num < 10: return 1 else: return 1 + count_digit(num/10) num = int(input("Enter a number to count: ")) print("Number of digits : % d" % (count_digit(num)))
Enter the number to count: 86759 Number of digits : 5
Hope you have enjoyed learning this article and learned how to find the number of digits of a number in Python.
You can also read, Python program to find the Nth Decagonal Number