-2

I am struggling to debug the following code, which throws a ZeroDivisionError:

if num > 0:
    return filter(lambda x: abs(num) % x == 0, range(1:abs(num))
else:
    pass

The error message is:

ZeroDivisionError: integer division or modulo by zero

The code is a bit ugly because I was getting this error before adding the if and abs() statements.

I am using python 3.6 per my schools requirement, and the task is to return factors of int num using a filter.

squalor
  • 33
  • 5
  • It isn't `num` that needs to be non-zero; it's `x`. Also, that's not how you use `range`. – TigerhawkT3 Mar 29 '17 at 22:39
  • 4
    [mcve], please. The code you've posted has syntactical errors that prevent it from running at all, and it wouldn't produce a ZeroDivisionError even if the syntax was fixed. – user2357112 Mar 29 '17 at 22:40
  • Thank you, I should have done better debugging before posting. I've been bashing my head against the wall too much today. – squalor Mar 29 '17 at 23:20

1 Answers1

-2

Your code returns this error because of how you have defined range().

The correct way to define range in python is below:

range(start, stop, step)

If your case you have used slicing, this is causing your program to throw error.

For your program you need to define a function is order to return something from conditional statements, the following code will solve your issue

def fac(num):
    if num > 0:
        return list(filter(lambda x: num % x == 0, range(1, num+1)))

print(fac(5))  # [1, 5]

Here I have used filter inside a list function because in Python 3 and above filter returns filter object.