Home > Software design >  ZeroDivisionError when listing factors of a number
ZeroDivisionError when listing factors of a number

Time:03-12

The program I am writing is tasked with creating a list of all possible factors of a number, excluding the number itself. My code is as follows:

def list_all_factors(num):
    result = []
    for i in range(0, num):
        if num % i == 0:
            result.append(i)
    return result

When I call this function I get the following error:

ZeroDivisionError: integer division or modulo by zero

What is causing this issue, and how can I resolve it?

CodePudding user response:

The for loop:

for i in range(0, num)

should be

for i in range(1, num)

We change the lower bound to avoid attempting to divide by zero.

CodePudding user response:

That's because you are trying to divide by zero as the error says in the for loop. You should start the range from 1 and add 1 to the upper bound to make sure it's included.

def list_all_factors(num):
    result = []
    for i in range(1, num):
        if num % i == 0:
            result.append(i)
    return result

or list comprehension

def list_all_factors(num):
    result = [i for i in range(1,num) if num % i == 0]
    return result 
  • Related