Home > front end >  List All Factors - ZeroDivision Error - Python
List All Factors - ZeroDivision Error - Python

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

I am just wondering what is causing this issue and how would I resolve it?

CodePudding user response:

There's two issues in the for loop:

for i in range(0, num)

should be

for i in range(1, num   1)

We change the lower bound to avoid the division by zero error, and we change the upper bound to account for the fact that all numbers are factors of themselves (since range() has an exclusive upper bound).

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 1):
        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 1) if num % i == 0]
    return result 
  • Related