Wanderson Gasco
Wanderson Gasco

Reputation: 15

Is there a way to make this code less horrendous? Python 3

So I'm trying to get a number to be divided simultaneously by 1 through 7. How can I simplify the "if" part?

I'm a beginner so if possible make it simple to understand.

Thanks!

result = []

for _ in range(1, 9999):
    if _ % 1 == 0 and _ % 2 == 0 and _ % 3 == 0 and _ % 4 == 0 and _ % 5 == 0 and _ % 6 == 0 and _ % 7 == 0:
        result.append(_)

print(result)

Upvotes: 1

Views: 32

Answers (1)

If you use a variable you should NOT name it _, this character is used for when something needs to be assigned but is never used. Lastly, you are looking for the all(...) syntax I think:

result = []

for num in range(1, 9999):
    if all(num % x == 0 for x in range(1, 8)):
        result.append(num)

print(result)

or the one line:

result = [num for num in range(1, 9999) if all(num % x == 0 for x in range(1, 8))]

Upvotes: 3

Related Questions