Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'if x % 2: return True' , wouldn't that return True if the number was divisible by 2?

I don't understand how if not x % 2: return True works. Wouldn't that mean this if x is not divisible by two, return True? That's what i see in this code.

I see it as if not x % 2: return True would return the opposite of if a number is divisible by 2, return True.

I just don't understand how that part of the syntax works.

def is_even(x):
    if not x % 2:
        return True
    else:
        return False
like image 519
jay_sanc Avatar asked Dec 20 '15 20:12

jay_sanc


2 Answers

Wouldn't that mean this if x is not divisible by two, return True?

No, because when x is not divisible by 2 the result of x%2 would be a nonzero value, which will be evaluated as True by Python, so its not would be False.

Read more about Truth value testing in python.

like image 73
Mazdak Avatar answered Nov 15 '22 04:11

Mazdak


The modulo operator % returns the remainder of a division. If x is divisible by 2 ('even'), then the remainder is zero and x % 2 thus evaluates to zero (=False), which makes the whole expression True.

like image 32
Joe Zocker Avatar answered Nov 15 '22 05:11

Joe Zocker