-3
for x in range(-50,50):
    if 50 % x == 0:
        a.append(x)

For a homework question, I have to create a function that will find all the numbers between -50 and 50 that divide into 50 (e.g. 1,2,5,10..) However I run into ZeroDivisionError: integer division or modulo by zero, when I try to run this. If I try it then with x % 50 == 0: it works, but its returning numbers divisible by 50, which isn't what I want.

Any ideas how I could fix this up?

azulu
  • 15
  • 3
  • 1
    For homework read [how do I ask a homework question](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – baduker Mar 26 '21 at 10:21
  • 1
    Your problem is easily solvable by excluding the `0` special case: `if x and 50 % x == 0:`. the `and` will use a boolean shortcut and it the first operand is falsy (which includes `0`) it will not even consider the second operand. – Klaus D. Mar 26 '21 at 10:26

1 Answers1

2

You can't devide by zero. There multiple ways to fix this problem:

for x in range(-50,50):
    if x == 0:
        continue

    if 50 % x == 0:
        a.append(x)

or

for x in range(-50,50):
    try:
        if 50 % x == 0:
            a.append(x)
    except:
        continue
metatoaster
  • 17,419
  • 5
  • 55
  • 66
Felixx
  • 21
  • 3
  • Welcome to StackOverflow. For future reference, you may wish to use the [triple backtick code fence syntax](https://stackoverflow.com/editing-help#syntax-highlighting) to help enclose your code block and to ensure the example code be correctly indented such that they would be immediately useful, whether as an answer or any future questions. I have edited the answer to ensure your intent is preserved, please do feel free to select edit to see the syntax changes or view the [revisions](https://stackoverflow.com/posts/66815142/revisions) to see what was done. – metatoaster Mar 26 '21 at 10:42
  • 2
    Don't use a bare `except`. Since you want to catch an error if you divide by zero you should use `except ZeroDivisionError:`. – Matthias Mar 26 '21 at 11:12