The print statement is inside the function, so, yes, that’s it. There is no way for it to execute if the function is not called.
As for having the function print anythng, in my view that needs a rethink. When we look at the return statement it is a value (total). The operations of the function are essentially pure and only read values from the dictionaries as directed by the food list which computed values are accumulated to total
.
In other words, a slightly more sophisticated approach would be needed to add verbosity to the outputs. For now, all we will want to print is the total that is returned.
print (compute_bill(shopping_list))
As a general rule, functions should be free of print statements and just do what they are intended to do, and return as needed. Then print.
Let’s play around with this function a wee bit. When you complete the unit on Advanced topics it will make sense, so put this aside until then. It merely demonstrates the added logic we can use to handle output and leave functions to do their special job.
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def back_order(s):
return '\n'.join(['%s not served' % x for x in s]) if len(s) else None
def compute_bill(food):
total = 0
not_served = []
for item in food:
if stock[item] > 0:
total += prices[item]
else:
not_served += [item]
return (total, not_served)
shopping_list = ["banana", "orange", "apple"]
# unpack the call returns
total, not_served = compute_bill(shopping_list)
print ('Total: %.2f \n%s' % (total, back_order(not_served)))
Total: 5.50
apple not served