How Does This Code Work?


I have a quesion in the above code?

When we pass an argument in the variable ‘meal_with_tax’:

meal_with_tax = tax(meal_cost)

here when we use tax() the above defined tax function is called , but how is it running correctly while ‘meal_cost’ is passed in argument instead of ‘bill’ …asap reply will be appreciated as I dont want to proeed with doubts :slight_smile: cheers

1. What Good are Functions?

To understand why we use bill, you must first understand why we use parameters.

As of defining the function, the program does not know whether bill is a number, a string, a list, a dictionary, etc. As far as the program is concerned bill could be anything and, well, it could care less. It’s just a placeholder for whatever you pass into the function when you actually call it. In other words think of parameters like variables. Whenever you call a function, the argument you pass into it becomes the value for bill. For instance if you called:


You would essentially be telling the program to run tax(bill) except now, bill = meal_cost. Until a function is actually called, the parameters you have set are valueless placeholders. Once you call the function and pass in arguments for those parameters, they take on value and purpose. What I mean by this is, if you did the following:

def tax(bill):
    bill *= 1.08
    print "With tax: %f" % bill
    return bill

meal_cost = 100


Notice how I defined the function using bill as a parameter and then I called the function using meal_cost as an argument. This is telling the program to run the code within tax(bill) but replace all mentions of bill with meal_cost. Basically it does this:

meal_cost *= 108
print "With tax: %f" % meal_cost
return meal_cost

This is why we use bill as we do in the function.


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