How to counts the number of decimal digits in a positive integer in Python
The following snippet counts the number of decimal digits in a positive integer:
n = 40265 count = 0 while n != 0: count = count + 1 n = n // 10 print(count)
This snippet demonstrates an important pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time the loop body is executed. When the loop exits, count contains the result — the total number of times the loop body was executed, which is the same as the number of digits.
If we wanted to only count digits that are either 0 or 5, adding a conditional before incrementing the counter will do the trick:
n = 2574301453 count = 0 while n > 0: digit = n % 10 if digit == 0 or digit == 5: count = count + 1 n = n // 10 print(count)
The general form of the above program:
n = int(input("Enter the number: ")) this_int = int(input("Enter a positive integer: ")) that_int = int(input("Enter a positive integer: ")) count = 0 while n > 0: digit = n % 10 if digit == this_int or digit == that_int: count = count + 1 n = n // 10 print(count)
By Amit Pratap Singh, India