Write a function that checks whether a number is even.
is_even(n)
Return True if n is even, False otherwise.
is_even(4) // → True
is_even(7) // → False
is_even(0) // → True
is_even(-3) // → False
% is the modulo operator — n % 2 gives you the remainder when n is divided by 2. For any even number that remainder is always 0; for any odd number it's always 1 (or -1 for some negative odd numbers, but the comparison to 0 still works either way).
def is_even(n):
return n % 2 == 0
A common beginner instinct is to write this with an if:
def is_even(n):
if n % 2 == 0:
return True
else:
return False
This works, but it's doing extra work for nothing — n % 2 == 0 is already a boolean expression (True or False), so you can return it directly. Any time you find yourself writing if condition: return True else: return False, that whole block can collapse into return condition.
def is_even(n):
return n % 2 == 0
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.