Lecture Notes
Introduction to Programming and Algorithm Design (COP-1000)

Functions

This chapter introduces you to the use of functions. A function is really just a block of statements that can be given a name and called from anywhere in your program. This chapter explains how to use both functions provided by Python (built-in functions) and functions you write yourself (user-defined functions).


Function calls

  • Python has several built-in functions that you can call, either from the Python Shell or from within a program to perform a specific action
  • A function call looks like this:

function_name( argument, ... )

  • The function name is always followed by a set of parentheses, which may contain a list of values, called arguments; some functions take:
    • no arguments but the parentheses are still required
    • one argument which can be any expression (literal, variable or expression, which is evaluated before the function is called
    • more than one argument in which case the arguments are separated by commas
    • The number and type of each argument is determined by how the function is written; for Python functions, this is documented in the function's application programmer's interface (API) in IDLE use Help > Python Docs
  • Some functions return a value, which can be displayed or assigned to a variable:

>>> type(3)
<type 'int'>
>>> type(3 + 4.2)
<type 'float'>
>>> whatIsIt = type("Studio" + "60")
>>> print whatIsIt
<type 'str'>

  • Every value in a Python program is given a unique integer identifier, which can be determined by inspecting the return value of the built-in function id():

>>> id(5)
9786592
>>> x = 5    # x is assigned the value 5
>>> id(x)
9786592      # x "points" to where 5 is stored
>>> id(6)
9786580
>>> x = 6
>>> id(x)
9786580
>>> y = 5    # now y points to where 5 is stored
>>> id(y)   
9786592

  • Note: we are almost are never interested in the id of a variable, because, while it is useful to the Python interpreter, we don't particularly care where in memory it stores values

Type conversion

  • Some of the most useful built-in functions are those that convert a value from one type to another; these are:
    • int( str or float ) convert to int
    • float( str or int ) convert to float
    • str( int or float) convert to string
  • Note: a value is not converted "in place"; a temporary value of the converted type is created, which can be displayed, assigned to a variable, or used in composition
  • Examples:

>>> int("45")
45
>>> type( int("45") )     # composition
<type 'int'>
>>> twenty = "20"
>>> print 12 + int(twenty)
32
>>> print "PI = " + str(3.14159) + " or so."
PI = 3.14159 or so.

>>> float(99)
99.0
>>> float("99")
99.0
>>> float("99 Cokes")

Traceback (most recent call last):
  File "<pyshell#26>", line 1, in -toplevel-
    float("99 Cokes")
ValueError: invalid literal for float(): 99 Cokes

  • The last conversion fails because the entire string cannot be converted to a valid floating point number
  • The built-in conversion function float() is often useful to force floating point division (when both operands are integers) by changing one of the operands to a float; this is called type coersion
  • See example program gpa1.py
  • Built-in function round() is useful to round float values to any level of precision:

       round(floating_point_expression [, n])

    the optional n specifies how many decimal places to round to; if it is omitted, rounding is to a whole number

Math functions

  • Python, like other modern programming languages, has many predefined functions you can use
  • Some of these functions are built-in, meaning they are always available
  • Some functions are not built in, but grouped in packages of related functions and stored in a library; in Python, these packages are called modules
  • If a function is stored in a module, that module must be imported before you can use it; for example the sqrt() function is part of the math module, so in order to use it, you will first need to import the math module, whether working at the command line, or in a program:

>>> import math
>>> math.sqrt(9)
3.0

  • Note that the function is called using dot notation the function name is prefaced by the module name, and separated from it by a period (dot)
  • See the example program sqrt1.py
  • For a complete list of all functions in the math module, type help(math) in the Python shell (assuming you have already imported the math module)
  • Note that the math module also includes the constants math.pi and math.e which are accurate to 16 decimal places:

>>> print math.pi, math.e
3.14159265359 2.71828182846

  • All math functions return a float type

Composition

  • If an expression is provided as the argument in a function call, the expression is evaluated before the function is called
  • If an argument is an expression that includes a function call, the function is called and its return value used in evaluating the expression

Adding new functions

  • In addition to using Python's predefined functions, you can also write your own to modularize your program
  • In the programs you have written, you have defined a main function, then called the main function to execute the program
  • The syntax for a function definition is:

def functionName( parameter, ... ):
    statement
    ...

  • The keyword def starts the function definition
  • The functionName is a descriptive name of your choosing that follows the same rules as those for variable names
  • parameter is (optionally) one or more variable names that will be used to receive the value(s) of the argument(s) in the function call; functions do not need to have parameters
  • statement is one or more statements that make up the body of the function, and which are executed when the function is called; all statements are indented in the function definition
  • Note the colon at the end of the first line of the function definition it is required!
  • Remember that a function definition only states what a function will do when the function is called; just writing a definition does not cause the function to execute
  • See the example program newline.py, which follows the text example

Definitions and use

  • A couple of minor differences to note from the text
  • When you call a function in the Python shell, it must already have been defined
  • When you call a function in a program, at least the way newline.py is written, all the functions are defined before main is called; none of them were executed until called, but by that time they had all been defined

Flow of execution

  • The order in which statements in a program are executed is called flow of control
  • Execution always begins with the first statement in a program, and the flow of control proceeds one statement at a time, top-to-bottom, unless something alters it
  • Function definitions do not change the flow of control the function is defined and remembered for later use, but its statements are not executed
  • Function calls do alter the flow of control by transferring control to the first statement in the function called
  • In newline.py, the program starts with three function definitions; actual execution does not begin until main is called in the last line of the program

Parameters and arguments

  • We can define functions that accept values called arguments that the calling function specifies in the function call
  • These values are assigned to variables called parameters, whose names we include in the parameter list in the function definition
  • For example, here is a function definition with two parameters:

>>> def lastNameFirst( firstName, lastName ):
        print lastName + ', ' + firstName

  • The two parameters are firstName and lastName; they can be used inside the function just as regular variables can
  • Here is a call to the function:

>>> lastNameFirst( 'Tiger', 'Woods' )
Woods, Tiger

  • The calling function can use variables as well as literals for the arguments

>>> fn = 'Kaiser'
>>> ln = 'Sosei'
>>> lastNameFirst( fn, ln )
Sosei, Kaiser

  • Note that the variable names used as arguments do not have to match the parameter names it is the value of the the arguments that is assigned to the parameters
  • See the sample program fnln.py
  • See the sample program gpa2.py, which uses numeric arguments

Variables and parameters are local

  • Function definitions can also include new variables:

>>> def triangleArea( base, height ):
        area = 0.5 * base * height
        print "Area is", area

  • The parameters base and height, and the variable area are said to be local to the function triangleArea(), because the can only be referenced directly from within that function
  • The function can be called as we do any function:

>>> triangleArea(13, 9)
Area is 58.5

  • But you cannot access any of its local variables from outside the function:

>>> print area

Traceback (most recent call last):
  File "<pyshell#55>", line 1, in -toplevel-
    print area
NameError: name 'area' is not defined


Stack diagrams

  • The stack diagrams discussed in this section reinforce the idea that parameters and variables are local to the function in which they are defined

Fruitful functions and void functions

  • Functions can return a value to the calling function or not
  • The newline() and lastNameFirst() functions above did not return a value (although they did produce output to the monitor)
  • Math functions all return a value, which can be displayed or assigned to a variable
  • We can write functions that return a value by using the return keyword
  • See example program triArea.py and triArea2.py for functions that return a value
  • Functions that return values are called fruitful functions, and can be used in expressions
  • Non-fruitful functions do not return a value, and must be called in a statement by themselves they cannot be used in an expression; non-fruitful functions are also called void functions
 Updated: 12.13.2010