Suppose you want to complete a function:
def isBetween(val, end1, end2): ''' True if the number val is between the numbers end1 and end2, allowing equality on either end. False otherwise.'''
We want to test if end1 <= val <= end2. And since the order of end1 and end2 were not specified, it might be that end2 <= val <= end1
A naive, newbie way to do this is to think of it as a decision and use an if statement:
if end1 <= val <= end2 or end2 <= val <= end1: return True else: return False
This certainly works, but we have a boolean test condition AND we are also returning a boolean value. Compare:
If the condition is True, the result is True.If the condition is False, the result is False.
In other words, we are just returning the condition value! There is a much shorter way to do that than with an if statement:
def isBetween(val, end1, end2): ''' True if the number val is between the numbers end1 and end2, allowing equality on either end. False otherwise.''' return end1 <= val <= end2 or end2 <= val <= end1
If we only wanted to do such a calculation once, we might eliminate the separate function, and assign directly to a boolean variable, say between. Again this works:
if end1 <= val <= end2 or end2 <= val <= end1: between = True else: between = False
And again that is verbose. Instead:
between = end1 <= val <= end2 or end2 <= val <= end1
Though not required (because of the low precedence of =), you might find this easier for humans to read with parentheses:
between = (end1 <= val <= end2 or end2 <= val <= end1)
A variation also works if you want the opposite boolean result, by using not:
outside = not (end1 <= val <= end2 or end2 <= val <= end1)
So remember: If you want to generate a boolean value, it is rarely efficient or concise to involve an ``if`` statement.
Exercise: Write efficient code to set the variable negVal to True only when the number x is negative, and set it to False otherwise.