Python Program to Count the Number of Digits in a Number

1. Introduction

In this tutorial, we will learn how to write a Python program to count the number of digits in a number.

Counting digits in a number involves determining how many individual digits make up the number. This can be done by repeatedly dividing the number by 10 until it's reduced to zero, counting how many times this division occurs.

2. Program Steps

1. Define a number whose digits are to be counted.

2. Initialize a count variable to keep track of the number of digits.

3. Use a while loop to divide the number by 10 until the number is greater than zero.

4. Increment the count variable with each division operation.

5. Print the count of digits.

3. Code Program

# Function to count digits in a number
def count_digits(n):
    # Initialize count to 0
    count = 0
    # Loop until the number is reduced to 0
    while n > 0:
        # Increment the digit count
        count += 1
        # Divide the number by 10 to remove the last digit
        n //= 10
    # Return the count of digits
    return count

# Number to count digits
number = 12345
# Call the function and store the result
digit_count = count_digits(number)
# Print the result
print(digit_count)

Output:

5

Explanation:

1. count_digits is a function that takes an integer n as its argument.

2. A variable count is initialized to 0 and will serve as a counter for the digits.

3. A while loop iterates as long as n is greater than 0.

4. Each iteration increments count by 1, which represents one digit of the number.

5. Inside the loop, n is divided by 10 using floor division (n //= 10), which removes the last digit from n.

6. When n is reduced to 0, the loop terminates, and the function returns the count, which is the total number of digits in the number.

7. The function count_digits is called with number (12345) as the argument, and the result (5) is printed, indicating that there are 5 digits in 12345.

Comments