6.4: Parameters
- Page ID
- 117559
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)By the end of this section you should be able to
- Identify a function's arguments and parameters.
- Describe how mutability affects how a function can modify arguments.
Arguments and parameters
What if a programmer wants to write a function that prints the contents of a list? Good practice is to pass values directly to a function rather than relying on global variables. A function argument is a value passed as input during a function call. A function parameter is a variable representing the input in the function definition. Note: The terms "argument" and "parameter" are sometimes used interchangeably in conversation and documentation.
Consider the following:
|
1 |
def print_welcome(name): |
|
2 |
print(f"Welcome {name}!") |
|
3 |
|
|
4 |
username = int(input("Enter new username: ")) |
|
5 |
print_welcome(username) |
Which is an argument?
nameusernamenameandusername
- Answer
-
b.
usernameis the argument passed toprint_welcome().nameisprint_welcome()'s parameter that is assigned withusername's value.
Which is a parameter?
nameusernamenameandusername
- Answer
-
a.
nameis the only parameter defined withprint_welcome().usernameis the argument passed on line 5's function call.
What is the scope of name?
print_welcome()only- whole program
- Answer
-
a.
nameis a parameter that exists only within a call toprint_welcome().
What would happen if username was changed to name on lines 4 and 5?
- same output
- error/wrong output
- Answer
-
a. The program would run correctly. Arguments and parameters can have the same name, and a local variable called
namewould still be created inprint_welcome(). Scope can be confusing with variables of the same name.
Multiple arguments and parameters
Functions can have multiple parameters. Ex: A function uses two parameters, length and width, to compute the square footage of a room. Function calls must use the correct order and number of arguments to avoid undesired behavior and errors (unless using optional or keyword arguments as discussed later).
def print_div(op_1, op_2):
""" Prints division operation """
print(f"{op_1}/{op_2} = {op_1/op_2}")
num_1 = 6
num_2 = 3
print_div(num_1, num_2) # Prints "6/3 = 2.0"
print_div(num_2, num_1) # Prints "3/6 = 0.5"
print_div(num_1) # Error: Missing argument: op_2
Consider the following:
def calc_distance(x1, y1, x2, y2):
dist = math.sqrt((x2-x1)**2 + (y2-y1)**2)
print(dist)
p1_x =int(input("Enter point 1's x: "))
p1_y =int(input("Enter point 1's y: "))
p2_x =int(input("Enter point 2's x: "))
p2_y =int(input("Enter point 2's y: "))
calc_distance(p1_x, p1_y, p2_x, p2_y)
Which is an argument?
p1_xx1
- Answer
-
a.
p1_xis the first argument used in line 9's function call.x1is defined as the first parameter ofcalc_distance().
Which is a parameter?
p1_yy1
- Answer
-
b.
y1is defined ascalc_distance()'s second parameter.p1_yis the second argument on line 9's function call.
What would be the value of x2 for the function call, calc_distance(2, 4, 3, 6)?
2436Error
- Answer
-
c.
3is a literal passed as the third argument, which corresponds tox2, the third parameter.
Modifying arguments and mutability
In Python, a variable is a name that refers to an object stored in memory, aka an object reference, so Python uses a pass-by-object-reference system. If an argument is changed in a function, the changes are kept or lost depending on the object's mutability. A mutable object can be modified after creation. A function's changes to the object then appear outside the function. An immutable object cannot be modified after creation. So a function must make a local copy to modify, and the local copy's changes don't appear outside the function.
Programmers should be cautious of modifying function arguments as these side effects can make programs difficult to debug and maintain.
What are the values of weekend_temps and type after convert_temps() finishes?
def convert_temps(temps, unit):
if unit == "F":
for i in range(len(temps)):
temps[i] = (temps[i]-32) * 5/9
unit = "C"
else:
for i in range(len(temps)):
temps[i] = (temps[i]*9/5) + 32
unit = "F"
# Weekend temperatures in Fahrenheit.
wknd_temps = [49.0, 51.0, 44.0]
deg_sign = u"\N{DEGREE SIGN}" # Unicode
metric = "F"
# Convert from Fahrenheit to Celsius.
convert_temps(wknd_temps, metric)
for temp in wknd_temps:
print(f"{temp:.2f}{deg_sign}{metric}", end=" ")
The output is 9.44°F 10.56°F 6.67°F. type was changed to "C" in the function but didn't keep the change outside of the function. Why is the list argument change kept and not the string argument change? (Hint: A list is mutable. A string is immutable.)
In convert_temps(), wknd_temps and temps refer to ________ in memory.
- the same object
- different objects
- Answer
-
a. A list is mutable, so the object referred to by
wknd_tempsandtempsis modified without needing a local copy.
After unit is assigned with "C", metric and unit refer to ________ in memory.
- the same object
- different objects
- Answer
-
b. A string is immutable, so
convert_temps()makes a new object forunitto refer to.
deg_sign is a string whose value cannot change once created. deg_sign is ________.
- immutable
- mutable
- Answer
-
a. An immutable object's value cannot be changed.
On line 16, unit ________.
- refers to an object with the value
"C" - does not exist
- Answer
-
b.
unitno longer exists afterconvert_temps()finishes and returns to line 14.
Write a function, print_area(), that takes in the base and height of a right triangle and prints the triangle's area. The area of a right triangle is
\(\frac{bh}{2}\), where \(b\) is the base and \(h\) is the height.
Given input:
3
4
The output is:
Triangle area: 6.0
Interactive Code
- Input
-
3
4 - Answer
-
def print_area(b, h):
area = (b * h) / 2.0
print("Triangle area:", area)base = float(input())
height = float(input())
print_area(base, height)
Write a function, print_scores(), that takes in a list of test scores and a number representing how many points to add. For each score, print the original score and the sum of the score and bonus. Make sure not to change the list.
Given function call:
print_scores([67, 68, 72, 71, 69], 10)
The output is:
67 would be updated to 77
68 would be updated to 78
72 would be updated to 82
71 would be updated to 81
69 would be updated to 79
Interactive Code
- Answer
-
def print_scores(scores, bonus):
for score in scores:
print(score, "would be updated to", score + bonus)print_scores([67, 68, 72, 71, 69], 10)
print() # Print newline
print_scores([67, 68, 72, 71, 69], 5)


