简体   繁体   中英

Function for finding all the numbers that divide into 50

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 (eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM