Write a Python Program to Count the Number of Digits Present In a Number

In Python, we can easily count the number of digits present in a given number using a simple algorithm.

Let’s take a look at the steps involved in this algorithm and how we can implement them in Python.


Algorithm

  1. Take input from the user.
  2. Initialize a counter variable to zero.
  3. Use a while loop to iterate through the digits of the number.
  4. Inside the while loop, increment the counter variable by one for each digit.
  5. Print the final value of the counter variable.

Python Code

num = int(input("Enter a number: ")) 
count = 0 while(num > 0): 
  num = num // 10 count = count + 1 
  print("The number of digits in the number are:", count)

In the above code, we first take input from the user using the input() function and convert it to an integer using the int() function.

We then initialize a counter variable count to zero.

The while loop is used to iterate through the digits of the number.

In each iteration of the loop, we divide the number by 10 using the // operator to remove the last digit, and then increment the counter variable by one.

The loop continues until all digits have been counted.

Finally, we print the final value of the counter variable using the print() function.


Conclusion

In this tutorial, we have discussed how to count the number of digits present in a number using Python.

We have provided a simple algorithm and the corresponding Python code to implement it.

With this knowledge, you can easily count the number of digits in any given number in Python.