Learning objectives
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.
Concepts in Practice
Arguments and parameters
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) |
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).
Example 6.1
Using multiple arguments in a function call
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
Concepts in Practice
Multiple arguments and parameters
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)
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.
Example 6.2
Converting temperatures
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.)
Concepts in Practice
Mutability and function arguments
Try It
Printing right triangle area
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 , where b is the base and h is the height.
Given input:
3 4
The output is:
Triangle area: 6.0
Try It
Curving scores
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