Parameters and arguments
Let's get back to our 2-line version of the function and its call:
def get_power(base, power):
result = base ** power
return result
print(get_power(3, 2))
This is what happens during the get_power(3, 2)
call:
base
andpower
parameters take values from the corresponding arguments3
and2
which were passed in the call. The order matters: the 1st argument becomes the value of the 1st parameter, the 2nd of the 2nd.- Parameters are used for exponentiation:
base ** power
. - The result of the exponentiation is returned.
Parameters can only be defined in one place: the function's header. Arguments can only be specified in one place: the function call. It's important to distinguish between parameters and arguments, especially because many sources (tutorials, blog posts, even some books) use these two terms inconsistently. Sometimes they are treated as synonyms, sometimes "arguments" is used to mean both parameters and arguments. There's also a term "actual parameter" which is a synonym of "argument", but it's rarely used. In our courses we are going to use these two terms in a strict and consistent way:
- Parameters are containers in the function definition made for incoming values.
- Arguments are incoming values specified in the function call.
It's easy to see the difference in that particular example, because, clearly, 3
and 2
are numbers. But, hopefully, you remember from the first course that variables can be used as arguments. Check this out:
length = 3
width = 2
def get_power(base, power):
result = base ** power
return result
print(get_power(length, width))
Now arguments (length
, width
) are identifiers, like parameters (base
, power
). This time the values of arguments come from variables. So, base
, power
are parameters, length
, width
are variables acting as arguments.
Both parameters and variables are identifiers, but used in different contexts:
- Variables are labels attached to values when the variables are created.
- Parameters are labels to refer to future values before they actually exist.
If you create a variable inside the body and give it the same name as one of the parameters, you'd make a classic programmer's mistake. No new variable would be created. Instead, the value of the parameter would change and the original argument value would be lost. This is very bad. Take a look:
def get_power(base, power):
base = 20
return base ** power
print(get_power(2, 3)) # →◼ 8000
Even though the call passed 2
as first argument, this value is lost and never used. This silly example is here to illustrate the point: do not name variables the same as parameters.
Note: symbols →◼
in the comment refer to the printed text. Alternatively, symbol →
without the black rectangle refers to the returned value.