Understanding the logic with conditions using return statement python

Question:

I have the following exercise from codingbat.com:

Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.

So, when I was solving it, I’ve formulated a simple logic as possible, based on previously exercises.

def pos_neg(a, b, negative):

  if (negative and (a < 0 and b < 0)):
    return True
  if (a < 0 and b > 0) or (a > 0 and b < 0):
    return True
  else:
    return False

But this solution does not work even if I declare "negative == True" on the second line,
giving me this table of answers:
Inputs and Outputs

I can’t figure out what could be wrong with the conditions, and how this logic differs from the correct answer:

def pos_neg(a, b, negative):
  if negative:
    return (a < 0 and b < 0)
  else:
    return ((a < 0 and b > 0) or (a > 0 and b < 0))

Also, I wished to know when it is correct to put the logical condition after the return statement.

Asked By: Guilherme RB

||

Answers:

It’s simple, your program fails because when your parameter "negative" is True, yes or yes, "a" and "b" must be negative.

But in your case whenever "a" or "b" are negative it will return True, even though "negative" is True.

One way to solve your problem is to simply make sure that "negative" is False when checking that "a" or "b" are negative (This does the same as the answer to the problem, just in a different way).

def pos_neg(a, b, negative):

  if (negative and (a < 0 and b < 0)):
    return True
  if (not negative) and ((a < 0 and b > 0) or (a > 0 and b < 0)):
    return True
  else:
    return False