Search code examples
pythonpython-3.xif-statementmodulus

How does this if statement determine whether num%2 is true or false


Okay, so here is a piece of code. The function of the code is to take a value and determine whether or not it is odd or even.

def isEvenOrOdd(num):
    return 'odd' if num % 2 else 'even'

Now my question lies in why this works. The way I am currently looking at this, is that --

num%2 returns a value. If num is 3, then num%2 = 1. Why would the value of '1' satisfy the 'if' condition?

I assumed this was a matter of 1 and 0, but I tried the same code with %4, and if 3 is returned, it still satisfies the if statement.

I understand this may be a basic question for some, so my apologies for perhaps being slow in understanding this. Thank you!


Thank you for your help ! I actually understand it now


Solution

  • The reason has to do with the "truthy-ness" of objects in Python. Every object in Python, even if it's not a boolean value, is considered "truthy" or "falsy". In this case, an integer is considered "truthy" if and only if it is not zero.

    Therefore, if the number is odd, its modulus will be 1 which is considered true. Otherwise, the modulus will be 0 which is considered false.

    If you switch the modulus to 4, the result will be truthy iff the remainder is not zero (i.e., if the number isn't a multiple of 4).