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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With