Pythondex
Python Programs

Count Number Of Zeros In A Number In Python

Published July 4, 2023 by Jarvis Silva

In this tutorial we will write a python program to count number of zeros present in a given digit, I will show you how to create this program in two ways first using for loop and second using recursion.

Count number of zeros in a number using for loop in python


def count_zeros(number):
    zero_count = 0
    number_str = str(number)
    
    for digit in number_str:
        if digit == '0':
            zero_count += 1
    
    return zero_count

# Example usage
number = 10204050
zeros = count_zeros(number)
print("Number of zeros:", zeros)


Output


Number of zeros: 4

In the code we have defined a function count_zeros() in that function we define a zero_count variable and also convert the number to string and then we use a for loop to iterate over the number string and in the for loop we check if there is a zero digit in the number if there then we increase the zero_count variable.

Count number of zeros in a number using for recursion in python


def count_zeros(number):
    # Base case: if the number is 0, return 1
    if number == 0:
        return 1
    
    # Base case: if the number is less than 10 and not 0, return 0
    if number < 10 and number != 0:
        return 0
    
    # Recursive case: divide the number by 10 and recursively count zeros in the remaining part
    return count_zeros(number // 10) + (number % 10 == 0)

# Example usage
number = 10204050
zeros = count_zeros(number)
print("Number of zeros:", zeros)


Output


Number of zeros: 4

In this code we have used recursion to count the number of zeros in a digit in python, in this we call the count_zeros() function inside the function itself.

You can run this program on your computer or use this online python compiler see the output yourself, I hope you found this tutorial helpful and useful.

Here are some more python tutorials you might find helpful:

Want free udemy coding course and more tutorials like this then join our telegram channel for free courses and updates of our tutorials.

Thanks for reading, have a nice day 🙂