0
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?

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Bobby
  • 11
  • 1
  • Modulo will divide the left hand expression by the right hand and return the remainder. So if you done `10 % 5` the remainder would be 0 since 10 is divisable by 5. If you dont `10 % 6` then the remainder would be 4. Now python if will evaluate an expression, So in the case of modulo you will return an `int` python will evaluate the truthyness of an int as 0 will be false and anything else will be true. – Chris Doyle Mar 28 '20 at 00:59

1 Answers1

1

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user2864740
  • 60,010
  • 15
  • 145
  • 220