Section 4.4 Function Parameters
Named functions are very useful because, once they are defined and we understand what they do, we can refer to them by name and no longer have to think too much about their inner workings. The functions then can be treated as separate tools that we can use repeatedly and in conjunction with other functions to solve a larger decomposed problem.
With parameters, functions are even more powerful, because they allow us to generalize a function’s actions so that it can do the same thing on each invocation, but with different starting values. With parameters our functions becomes adjustable tools that can be resused to solve different problems.
The figure below shows a function’s relationship with its parameters. A function needs certain information to do its specific work. These values, often called arguments, actual parameters or parameter values, are passed to the function by the code that invokes the function.
This type of diagram is often called a black-box diagram because it only states the requirements from the perspective of the ’user’ (well, the programmer, but the programmer who writes the code that uses the function, who may be different than the programmer who created the function - which, by the way, is why docstrings are so useful to explain a function). The ’user’ must know the name of the function and what arguments it needs to be passed. The details of how the function works are hidden inside the “black-box”.
You have already been making function invocations with parameters. For example, when you write
len("abc")
, len
is the name of a function, and the string “abc” is a parameter value. Or print("Answer", 3 - 4, sep=" is equal to ")
where the print function is passed three parameters: a string, an expression and a named parameter.When a function has one or more parameters, the following holds:
- The names of the parameters appear in the function definition
- The parameters are separated by commas
- The values in the parentheses of the function invocation are assigned to the parameters in the same order
In the function definition, the parameter list is sometimes referred to as the formal parameters, ideal parameters or parameter names. These names can be any valid variable name.
In the function invocation, inside the parentheses one value should be provided for each of the parameter names. These arguments can be specified directly (
"abc"
), by any Python expression (e.g. 3 - 4
) including a reference to some other variable or function name (abs(3 - 4)
), or by name (also known as keyword arguments - like speed = 5.4
or sep = " is equal to "
.That can get kind of confusing, so let’s start by looking at a function with just one parameter. The revised hello function personalizes the greeting: the person to greet is specified by the parameter.
First, notice that hello2 has one formal parameter,
s
. You can tell that because there is exactly one variable name inside the parentheses on line 1 (the colon and the ’str’ are part of Type Annotation, a topic we will discuss shortly).Next, notice what happened during Step 2. Control was passed to the function, just like we saw before. But in addition, the variable
s
was bound to a value, the string “Iman”. When it got to Step 7, for the second invocation of the function, who
was bound to “Jackie”.Function invocations always work that way. The expression inside the parentheses on the line that invokes the function is evaluated before control is passed to the function. The value is assigned to the corresponding formal parameter. Then, when the code block inside the function is executing, it can refer to that formal parameter and get its value, the value that was passed into the function.
To get a feel for that, let’s invoke hello2 using some more complicated expressions, but one where we use more self-documenting parameter names. Feel free to modify things on your own - allowing them to ’break’ but then fixing things too.
Now let’s consider a function with two (not all that self-documenting) parameters. Can you determine what the two variables are? What they are for?
At Step 2 of the execution, in the first invocation of hello3, notice that the variable
s
is bound to the value “Wei” and the variable n
is bound to the value 4.That’s how function invocations always work. Each of the comma separated expressions inside the parentheses are evaluated to produce values. Then those values are matched up positionally (in the same order) with the formal parameters of the function definition. The first parameter name is bound to the first value provided. The second parameter name is bound to the second value provided. And so on.
Try writing your own version of the program above, but pass the arguments in the reverse order, e.g.
hello3(4, "Wei")
. What happens when you run the code? It should produce a runtime error - an error that happens when the code is syntactically correct and runs, but encounters an issue during execution; in this case, it can’t deal with the variables being of a different than expected data type.Check your understanding
Checkpoint 4.4.2.
- def greet(t: str) -> None:
- A function may take zero or more parameters. In this case it has one.
- def greet:
- A function needs to specify its parameters in its header. If there are no paramters, put () after the function name.
- greet(t: str, n: int) -> None:
- A function definition needs to include the keyword def.
- def greet(t: str, n: int) -> None
- A function definition header must end in a colon (:).
Which of the following is a valid function header (first line of a function definition)?
Checkpoint 4.4.3.
- def print_many(x: str, y: int) -> None:
- This line is the complete function header (except for the semi-colon) which includes the name as well as several other components.
- print_many
- Yes, the name of the function is given after the keyword def and before the list of parameters.
- print_many(x: str, y: int)
- This includes the function name and its parameters
- Print out string x, y times.
- This is a comment stating what the function does.
What is the name of the following function?
def print_many(x: str, y: int) -> None:
"""Print out string x, y times."""
message = x * y
print(message)
Checkpoint 4.4.4.
- i
- i is a variable used inside of the function, but not a parameter, which is passed in to the function.
- x
- x is only one of the parameters to this function.
- x, y
- Yes, the function specifies two parameters: a string x and an int y.
- x, y, i
- the parameters include only those variables whose values that the function expects to receive as input. They are specified in the header of the function.
What are the parameters of the following function?
def print_many(x: str, y: int) -> None:
"""Print out string x, y times."""
message = x * y
print(message)
Checkpoint 4.4.5.
- print_many(x, y)
- No, x and y are the names of the formal parameters to this function. When the function is called, it requires actual values to be passed in.
- print_many
- A function call always requires parentheses after the name of the function.
- print_many("Greetings")
- This function takes two parameters (arguments)
- print_many("Greetings", 10):
- A colon is only required in a function definition. It will cause an error with a function call.
- print_many("Greetings", z)
- Since z has the value 3, we have passed in two correct values for this function. "Greetings" will be printed 3 times.
Considering the function below, which of the following statements correctly invokes, or calls, this function (i.e., causes it to run)?
def print_many(x: str, y: int) -> None:
"""Print out string x, y times."""
message = x * y
print(message)
z = 3
Checkpoint 4.4.6.
- 7
- n3 was given a value; it would be included in the returned value.
- 15
- 4 + 3 - (-8) is 15.
- -1
- n3 is a negative number that is subtracted from the sum of n1 and n2.
- The function would produce an error.
- This code contains no errors.
What output will the following code produce?
CONSTANT_VALUE = -8
def cyu(n1: int, n2: int) -> int:
print(n1 + n2 - CONSTANT_VALUE)
cyu(4, 3)
You have attempted of activities on this page.