d0rmLife
d0rmLife

Reputation: 4250

How to test several modulo values in one line with Python?

Suppose I have a value that could be in the range of [28,32] or a multiple of a number in that range.

Is there a way that I can test this in one line using the modulo operator?

Tried:

if value % (28 or 29 or 30 or 31 or 32) == 0:
    # do stuff

And some similar variations. I tried to search, as I'm sure this is a common operation, but I couldn't find an answer.

Upvotes: 1

Views: 946

Answers (2)

Chad S.
Chad S.

Reputation: 6633

This is a job for any

   if any( value % m == 0 for m in range(28,33) ):
       #do stuff

Upvotes: 5

Kevin
Kevin

Reputation: 76194

You can use any to check the truthiness of multiple similar expressions:

if any(value % n == 0 for n in (28, 29, 30, 31, 32)):

Upvotes: 4

Related Questions