As part of this exercise, the function has to add up the values for 4 parameters (food_bill, electricity_bill, internet_bill, rent) and compare against the budget parameter. If a list of expenses was provided instead of individual parameters, how could those be added easily?
Answer
The sum() function is provided by Python to easily add up a list of items. If given a list of numeric values, the sum() function will add them up and return the value of the summation.
but if I write like this:
def over_budget(budget,food_bill,electricity_bill,internet_bill,rent):
if budget<sum(food_bill,electricity_bill,internet_bill,rent):
return True
It gave me this: sum expected 2 arguments, got 4
Could you help explaining me why this error happened here?
first argument passed to function is assigned to a, any folowing arguments are assigned to list variable b. The sum() expects a list as argument so just passing over the obtained b list is enough.
read more about packing and unpacking variables args and kwargs