Is it necessary to manually return True or False?

def over_budget(budget, food_bill, electricity_bill, internet_bill, rent):
  bills = [food_bill, electricity_bill, internet_bill, rent]
  if sum(bills) > budget:
    return True
  else:
    return False

The construction,

if <condition>:
    return True
else:
    return False

… is rarely used; assuming that <condition> is a boolean expression that you can expect to return either True or False, all you need is

return <condition>

3 Likes

I see the example / question being a bit ridiculous, but I would argue for the sake of completeness and self documenting code that a Boolean function should return a value within the confines of the scope of the expected result. A Boolean should be exactly that either a true or false, 1, or 0, but never a null or empty. I would further argue that that is what makes the difference between a hack that can code and a programmer that can produce a consistently expected result when code is executed.

Admittedly, the example, below, that is provided by the hint in the exercise could be improved:

if a < b + c + d:
  return True 

Following @patrickd314’s pattern, it could better be written as:

  return a < b + c + d

That would be concise, and would return either True or False, based on the evaluation of the condition.

2 Likes

For comparison operators, quite so. But you must exercise a bit of care with and and or:

a = 5 > 2
b = 3 < 1

print(a or b)
print(a and b)

print([] or "aardvark" )

print(a and max(6, 7))
print(a and {})

Output:

True
False
aardvark
7
{}
2 Likes

As an example of what I think Patrick was saying this is the code I used, and I don’t explicitly return True or False.

def over_budget(budget, food_bill, electricity_bill, internet_bill, rent):
  return budget < (food_bill + electricity_bill + internet_bill + rent)

Fortunately Python makes it possible to be less verbose on the function end of transactions. This may be jumping the queue a tad, but here we go…

>>> def over_budget(budget, *args):
  return budget < sum(args)

>>> food_bill, electricity_bill, internet_bill, rent = 800, 100, 80, 1000
>>> expenses = food_bill, electricity_bill, internet_bill, rent
>>> budget = 2000
>>> over_budget(budget, expenses)
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    over_budget(budget, expenses)
  File "<pyshell#38>", line 2, in over_budget
    return budget < sum(args)
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
>>> over_budget(budget, *expenses)
False
>>> 

Study how the splat operator solved the TypeError. It unpacks the tuple in the argument.