Skip to main content

Section 10.1 Average Numbers

Subgoals for writing functions:.

  1. Define and initialize global variables
  2. Write function header with function name and parameters (must include () even without parameters)
    1. Optional -- Set default values for parameters
  3. Write function body
    1. Distinguish between global and local variables based on indentation
  4. Determine what to return, if anything, to call site
  5. Call function with appropriate arguments

Subsection 10.1.1

Problem: Define a function average3 that consumes three integers and produces a new integer that is the truncated average of the numbers. Use the function to calculate the average of the numbers 100, 300, and 150.

Subsection 10.1.2 1. Define and initialize global variables

This function does not require any global variables.

Subsection 10.1.3 2. Write function header with function name and parameters (must include () even without parameters)

We only know that the three parameters are integers, so their names are fairly generic.
def average3(num1, num2, num3):
    pass

Subsection 10.1.4 3. Write function body

def average3(num1, num2, num3):
    result = (num1 + num2 + num3) // 3

Subsection 10.1.5 4. Determine what to return, if anything, to call site

The function is meant to return the result of the expression, so that is what is returned.
def average3(num1, num2, num3):
    result = (num1 + num2 + num3) // 3
    return result

Subsection 10.1.6 5. Call function with appropriate arguments

We can call the function with the desired arguments:
average3(100, 300, 150)
Answer.
We must also remember to print the result, if we want to see the final result.
def average3(num1, num2, num3):
    result = (num1 + num2 + num3) // 3
    return result

print(average3(100, 300, 150))
You have attempted of activities on this page.