Positive Negative - Simple Python exercise
<p>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.</p>

<p>I finally figured it out.</p>

<pre><code>def pos_neg(a, b, negative):
  if negative:
    return (a &lt; 0 and b &lt; 0)
  else:
    return (a &gt; 0 and b &lt; 0) or (a &lt; 0 and b &gt; 0)
</code></pre>

<p>But... why do I return those two lines instead of True? How do I know to do this in a similar situation?</p>

<p>Python evaluates whatever expression follows the <code>return</code> statement, and the result of the evaluation is what is returned.  You have used two boolean expressions:</p>

<pre><code>(a &lt; 0 and b &lt; 0)
</code></pre>

<p>This evaluates to True if both a &lt; 0 and b &lt; 0; otherwise it evaluates to False</p>

<pre><code>(a &gt; 0 and b &lt; 0) or (a &lt; 0 and b &gt; 0)
</code></pre>

<p>This evaluates to True if either of the parentheses evaluate to True; otherwise it evaluates to False</p>

<p>which is what you want. So <code>pos_neg</code> automatically returns either True or False depending on the specified inputs.</p>

<p>Perhaps you were thinking of testing each condition for True/False, then using an <code>if</code> statement to <code>return True</code> if the condition is True and to <code>return False</code> if the condition is False. That would work, but would be unnecessarily long and complex. Here, you are just returning with whatever the boolean value of each expression works out to be, whether it's <code>True</code> or <code>False</code>.</p>

python