Understanding Functions


#1

Hello all,

I thought I had a good handle on functions thus far, but I can’t seem to grasp what is occurring. Big ask, but can someone help break down what is happening in this code? As in, from start to finish, the order of operations occurring? I think seeing that will go a long way. Thanks so much!


#2

What is it you do not understand?

def foo(param):
    return param

The above is a function definition that returns its parameter. In math we would call this an identity function.

print foo('bar')    # bar

The above is a call expression with the return value being sent to the display.

In your code above the call to tax() stores its return value in meal_with_tax, and the call to tip() stores its return value in meal_with_tip. At each line, the value is increased, The final value, meal_with_tip is the total due for the meal.


#3

Here. I’ll break it down by line as I understand it. So:

  1. Define function “tax” with parameter “bill”
  2. Comment
    3 . “bill” equals “bill” multiplied by 1.08
  3. We print a string and it replaces “%f” with the argument fed to “bill.”
  4. Don’t fully understand return, but I believe the purpose is to solidify, so to speak, the new value of “bill” so that we can use that new value for the lines below.

My question is: how are we feeding these arguments? Does it go that:

  1. “100” (because of being defined on line 13 as such) is the argument fed into “bill” because the function “tax” is being called only with the “meal_cost” parameter now taking the place of “bill”?

A bigger question for me is: how do these steps work out in terms of order? Like, Line 4 can’t really print until it has gone through line 14, yes? So, does it break down in the following order of operations?

Line: 1, 13, 14, 3 4, 5, 7, 15, 9, 10, 11

Apologies if I’ve made this very convoluted/did not explain myself well. Very, very new. Thanks for all your help!


#4

When we pass meal_cost to the tax function, it’s value is copied to the local variable, bill so now bill is 100. Inside the function it gets augmented by the amount of tax so becomes 108 in the return value. That is the value that gets stored in meal_with_tax. When that value is passed to the tip function, again it is copied to a local variable, bill, and further augmented by the amount of the tip and it is that return value that is stored in meal_with_tip. The final amount should be 124.20.

When working with currency, use only 2 decimal places in the print formatting.

>>> print "%.2f" % 124.19999999999999
124.20
>>> 

#5

Ah! Seeing that order of operations did help big time! I was getting lost while going through, but I can see this now. Thank you so much!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.