Glenn Blakney
Glenn Blakney

Reputation: 33

Modulo Operator on a set in Python

How do I use the modulo operator on a set of numbers?

if value > 2 and value % 2 == 0 or value % 3 == 0 or value % 5 == 0 or value % 7 == 0 or value % 11 == 0: 
    return False

How do I consolidate all those "or" statements into something more elegant like "and value % set == 0"?

Upvotes: 3

Views: 442

Answers (4)

user13914826
user13914826

Reputation:

Try this:

def Fun(value):
    if value > 2 and any([value%x==0 for x in [2, 3, 5, 7, 11]]):
        return False
    return True

Upvotes: 0

Gavin Wong
Gavin Wong

Reputation: 1260

numbers = [2, 3, 5, 7, 11]

value = #define value here

def modulo():
    for number in numbers:
        if value > 2:
            if value % number == 0:
                return False

modulo()

Upvotes: 0

azro
azro

Reputation: 54148

Use any which

Return True if bool(x) is True for any x in the iterable

checks = {2, 3, 5, 7, 9}
if value > 2 and any(value % check == 0 for check in checks):
    return False

Upvotes: 1

Jan
Jan

Reputation: 43169

You may use any(...):

value = 100

if value > 2 and (any(value % x == 0 for x in [2, 3, 5, 7, 11])):
    print(False)

Upvotes: 4

Related Questions