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

Viewed 112

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

2 Answers

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).

in python the, some data types has a true value or a false value, it doesn't have to be a boolean. for example

test = None
if test:
  print("working")
else:
  print("Not working")

you will notice you get an ouput of Not working the reason is for object None is regarded as False same applies for some other data type , for integer, as long as a value is zero (0) it will take it as False

So in your case, if num % 2 return 0 then you will have

'odd' if 0 else 'even' # will will return 'even'
Related