Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Engineering LibreTexts

6.4: Parameters

( \newcommand{\kernel}{\mathrm{null}\,}\)

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.

Checkpoint: Global and local variables in a program with a function
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)
1.
Which is an argument?
  1. name
  2. username
  3. name and username
2.
Which is a parameter?
  1. name
  2. username
  3. name and username
3.
What is the scope of name?
  1. print_welcome() only
  2. whole program
4.
What would happen if username was changed to name on lines 4 and 5?
  1. same output
  2. error/wrong output

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)
5.
Which is an argument?
  1. p1_x
  • x1
  • 6.
    Which is a parameter?
    1. p1_y
    2. y1
    7.
    What would be the value of x2 for the function call, calc_distance(2, 4, 3, 6)?
    1. 2
    2. 4
    3. 3
    4. 6
    5. Error

    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.)

    Checkpoint: Exploring a faulty function
    Concepts in Practice: Mutability and function arguments
    8.
    In convert_temps(), wknd_temps and temps refer to ________ in memory.
    1. the same object
  • different objects
  • 9.
    After unit is assigned with "C", metric and unit refer to ________ in memory.
    1. the same object
    2. different objects
    10.
    deg_sign is a string whose value cannot change once created. deg_sign is ________.
    1. immutable
    2. mutable
    11.
    On line 16, unit ________.
    1. refers to an object with the value "C"
    2. does not exist
    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 bh2, 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

    This page titled 6.4: Parameters is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.

    Support Center

    How can we help?