samedi 4 juillet 2020

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!

Aucun commentaire:

Enregistrer un commentaire