Defining Functions

Functions allow the statements required to perform a specific task to be grouped together and given a name.

Using the function name causes the group of statements with the corresponding name to be executed.

Some of the material below is repeated from the Using Functions notes.

Two Important Pieces for Function Use

There are 2 important pieces to the use of functions:

  1. Function call
  2. Function definition

Both pieces are required.

Often the term function is used alone and from the context listener knows whether it is a function call or a function definition that is being referred to.

Function Call

Function call - A function call is a use of the function name that causes the statements of the function definition to be executed.

A function call has the form:

function_name(optional_parameter_list)

A function call consists of a function name followed by parentheses, which optionally contain a comma separated list of expressions.

Function Definition

Function definition - A function definition causes a function to be created and provides:

  • The function name
  • The parameters given to the function
  • The statements to be executed when the function is called

We will see function definitions below.

Function Call Example

Assume a function named search exists that will:

  • Search a given list for a given name, and
  • Has a result that is:
    • The index in the list where the name occurred, or
    • -1 if the name is not in the list

# Set up some variables

names = ['Harry', 'Hermoine', 'Rob']
person = 'Rob'

# Function call, result assigned to variable idx
idx = search(names, person)

# Use the result
if idx != -1:
   print(person, 'is in the list at index', idx)
else:
   print(person, 'is NOT in the list')

# This function works by result, no side effect.

Function Definition - Black Box

Think of a function definition, like for the previous search function, as a black box.

Input is given, a result is given back, and the details of how the result is arrived at are unknown and not of concern.

Clearly the input and output are important.

  • Parameter Passing - The mechanism for sending giving information to the function definition (from the call). (The input.)
  • return Statement - The mechanism for sending a result from the function definition back to the call. (The output.)

Function Definition - Python

Function definitions in Python have the form:

def function_name(optional_parameter_list):
   function body

The purpose of each part is,

  • def - required syntax
  • function_name - the name given to the function.
  • optional_parameter_list - The parameter list is optional. The parameter list is a list of variable names.
  • : (colon) - required syntax
  • function body - the statements that will be executed when the function is called.

Example Definition (Partial) and Call

# Function Definition
def sqrt(num):
   # Accuracy
   accuracy = 0.000001
   # Compute the square root ...

# Function Call
number = input('Enter a number: ')
root = sqrt(number)

Both the call and the definition are required.

The definition may be:

  • Built-in, part of the language
  • Provided in a module (another file)
  • In the same file as the call.
    In this case the definition must occur before the call in the file.

Parameter Passing

For a function to do something useful it must have something to "work on".

Values in the function call are made available in the function definition automatically by the parameter passing mechanism..

Parameter passing causes the variable in the function definition to have the same value as the positionally corresponding variable in the call.

# Function Definition
def search(list, target):
   # Search the list ...

# Function Call
idx = search(names_list, person)

In the above example when the search function begins executing:

  • The variable list will be given the value of the variable names_list
  • The variable target will be given the value of the variable person

When a person writes a function (definition) the person does not know what specific variables will be used in the call but the person knows that the parameters in the function being written will have values when the function definition executes.

The authors of the functions used so far (len, input, print, etc.) could not have known how future users would call those functions.

Note:

  • The variables in the parameter list are separate, dictinct names from the variables in the call and those names in the parameter list are only usable in the function definition.
  • The parameter variables in the definition are given values by the parameter passing mechanism when the function definition begins executing

Function Return Statement

When the return statement is executed:

  1. The function execution is done, any statements that follow in the function definition are skipped
  2. A value is "sent back"
  3. Execution resumes at the function call, often with the result (the returned value) used in an expression or with the assignment of the result of the call to a variable.

Function Return Statement - Example

def find_greatest(var):
   ...
   return value

# Get a list, do the call, output the result
numbers = [3, 12, 9, 6]
result = find_greatest(numbers)
print('The greatest value is', result)

Functions - Result and Side Effect

A function accomplishes its task by returning a result, causing a side effect, or doing both.

A function has a result by returning a value.

A function causes a side effect by:

  • Changing the a parameter so that it is changed in the call.
  • Performing output
  • Performing input
  • Changing a global variable (discussed later)

Function Example - Result

A function that takes three parameters and returns the sum of the parameters.

# Function definition
def sum3(v1, v2, v3):
   # Compute sum
   sum = v1 + v2 + v3
   # Return result
   return sum

# Some variables for the paramters
n1 = 22
n2 = 88
n3 = 10

# Use (call) the function
x = sum3(n1, n2, n3)

# Output result
print('Sum is', x)

Function Example - Side Effect

This function simply outputs a greeting:

# Function definition
def greet(name):
   # Remove leading and trailing whitespace in name, if present
   msg = 'Hello ' + name.strip() + '!'
   # Output
   print(msg)

# Some variables for the paramters
n1 = 'Frodo'
n2 = ' Sam '

# Use (call) the function
greet(n1)
greet(n2)

Note the greet function does not return a value and there is no assignment of a value at the calls.

Function Definition Example - search

We define a function named search that will search a given list for a given name and has a result that is the index in the list where the name occurred or -1 if the name is not in the list.

# Function definition
def search(items, target):
   # Go through the items in the list, return if target is found
   idx = 0
   while idx < len(items):
       if items[idx] == target:
           return idx
       # Increment index
       idx = idx + 1
   # Not in the list
   return -1

Using the search Function

Once the function has been defined it may be used (called).

# List to search and a target to search for
beatles = ['John', 'Paul', 'George', 'Ringo']
target = input('Enter a name: ')

# Use the search function
found = search(beatles, target)
if found != -1:
   print(target, 'is a Beatle')
else:
   print(target, 'is NOT a Beatle'

The definition must occur before the call.

Function Benefits

Abstraction - Abstraction is taking a conceptual view of an object or task that ignores the details of construction or implementation.

  • Abstraction, the function user can think at a "higher level", that is, in terms of the task a function performs rather than the details required to accomplish the task. For example, square roots.
  • Functions aid in the construction of large programs from smaller pieces.
  • The pieces (functions) may be tested and debugged separately.
  • code reuse - others may use an existing function (definition).
  • Repetition of the same code can be avoided, the code can be put in a function and called repeatedly.
  • The implementation of the task (the function definition) may be changed without affecting the programs that use it.