I need help with this python exercise

please give me the full working solution and explain it, thank you!

Instead of trying to write code for the specific test cases, look at the problem they are asking you to solve. You need a condition that checks whether inputs are even. I suggest looking at the mod operator.

1 Like

You are only testing for whether one of your numbers is even before calling return. Once you call return, the code moves out of the function. Try using a complex conditional statement that tests both arguments for being even as well as being less than nine and return the result of that conditional.

1 Like
def is_either_even_and_less_than_9(some_num1, some_num2):
    return (some_num1 % 2 == 0 or some_num2 % 2 == 0) and some_num1 < 9 and some_num2 < 9

The logic is simple. The question states:
"if either: so we use or
AND both are …: so we use and

From a logic table, we know that:
True and True =True
True and False = False
F and T = F
F and F = F

Also:
T or T = T
T or F = T
F or T = T
F or F = F

Which results in:

  • is even check: (is_even(some_num1) or is_even(some_num2)

  • Both are less than nine: some_num1 < 9 and some_num2 < 9

  • Next case1 AND case2 need to be True: (... or ...) and (x < 9 and y < 9)

So we can write our conditions anyway you would like, I just wrote them in-line in my example, but we could’ve written other functions outside or inside our function.

Outside example:

def is_even(num):
    return num % 2 == 0
# funtion name uses the acronym for less than, lowercase LT, if fonts make it hard to distinguish
def lt_nine(num):
    return num < 9

def ungodly_long_function_name_for_some_reason(x, y):
    return (is_even(x) or is_even(y)) and lt_nine(x) and lt_nine(y)

Inside Example:

def special_tester(num1, num2):
    """Returns True if both numbers are less than nine, AND either number is even"""
    is_even = lambda x: x % 2 == 0   #anonymous function assigned to a variable
    lt_nine = lambda x: x < 9        #x just servers as the argument/parameter
    return (is_even(num1) or is_even(num2) and lt_nine(num1) and lt_nine(num2)
1 Like
def is_even_and_less_than_9(num1, num2):
    return (not num1%2 or not num2%2) and sorted([num1, num2, 8])[-1] == 8