Bobby
Bobby

Reputation: 11

Can you explain the use of modulo operator in an if statement

m = 1
my_list_1 = [2 , 4, 1]
for x in my_list_1:
    for y in range(1,3):
        if (x + y) % 3:
            m = m * x
print (m)

In line 5, what does the modulo operator do. Doesn't is need something like == 1?

Upvotes: 0

Views: 364

Answers (1)

user2864740
user2864740

Reputation: 61905

Doesn't is need something like == 1?

No, it does not.

See https://docs.python.org/3/reference/expressions.html#booleans - if works on the result of any expression; it need not be a strict True and False, nor must there be any comparison operator involved.

In the context of Boolean operations, and also when expressions are used by control flow statements [like if], the following values are interpreted as false: False, None, numeric zero (0) of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

The relevant cases are % returns zero or non-zero.

Zero is considered a false-y expression, and Non-Zero is a truth-y expression.

if 0:
  print("Not here!")

if 1:
  print("Here!")

So the code is equivalent to using an explicit comparison:

if ((x + y) % 3) != 0:    # eg. if the remainder is 1 or 2 (but not 0),
    m = m * x             #     as non-zero numeric is truth-y

Upvotes: 1

Related Questions