Search code examples
pythonpython-3.xfunctiondivide-by-zero

Zero division error in python function even after using if-statement to avoid division by 0


I am writing a function that returns the total count of digits(of an integer) that can divide the integer that it is a part of. For ex- Integer -111 count - 3 as all 1,1,1 divide 111 Integer - 103456 count - 2 only divisible by 1,4. To handle the special case of division by 0 , I have used if-else statements .However, I am still getting a zero divison error. Why am I still getting this error? My error message:-ZeroDivisionError:integer division or modulo by zero

My code-

    count=0
    divisors_list=[]
    number_in_string = str(n)
    divisors_list=list(number_in_string)
    for divisor in divisors_list:
       if divisor != 0:
            if n%int(divisor) == 0:
               count+=1
    return count

x=findDigits(103456)

Solution

  • The issue is bad usage of strings as integers.

    One way to fix your code is:

    def findDigits(n):
        count = 0
        number_in_string = str(n)
        divisors_list = list(number_in_string)
        for divisor in divisors_list:
            # *** at this point, divisor is a string ***
            divisor = int(divisor)  # <== cast it to int
            if divisor != 0:
                if n % divisor == 0:
                   count += 1
        return count