CH 05
CH 05
A program as groups of statements called functions, each of which accomplishes a specific task
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 1
Motivation
So far, we learned the most fundamental features of Python:
variables, expressions, control structures, input/print, lists.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 3
In order to manage such complexity, we divide a program
into manageable pieces called functions (or routines)
...
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 5
What is a Function (Routine)?
while ( … ) :
stmt1
stmt2
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 6
Function A()
stmt1
. while (…) :
worker4 worker5
• Following the function header is the function body, a suite (program block)
containing the function’s statements. As with all suites, the statements must be
indented at the same level, relative to the function header.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 10
The number of items in a parameter list indicates the number of values that
must be passed to the function, called actual parameters (arguments) (or
simply “arguments”), such as variables num1, num2, and num3 below.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 11
Value-Returning Functions
f(x) = 2x
In this notation, “x” stands for any numeric value that function f may be
applied to,
f(2) = 2 x 2 = 4
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 12
Function avg takes three arguments (n1, n2, and n3) and returns the
average of the three. The function call avg(10, 25, 16), therefore, is
an expression that evaluates to the returned function value. This is
indicated in the function’s return statement of the form return expr,
where expr may be any expression.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 13
Let’s Try It
From the Python Shell, first enter the following function, making sure to
indent the code as given. Hit return twice after the last line of the function
is entered. Then enter the following function calls and observe the results.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 14
Non-Value-Returning Functions
A non-value-returning function is called not for a returned value, but for its
side effects. A side effect is an action other than returning a function value,
such as displaying output on the screen.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 15
Let’s Try It
From the Python Shell, first enter the following function, making sure to
indent the code as given. Then enter the following function calls and
observe the results.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 16
Function Call Overview
• A call to a value-returning function is an expression. It evaluates to the
value returned by the function call. Thus, calls to value-returning
functions are made part of a larger expression or instruction,
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 17
Let’s Apply It
Temperature Conversion Program
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 18
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 19
In lines 3–33 are defined functions
displayWelcome, getConvertTo,
displayFahrenToCelsius, and
displayCelsiusToFahren. The
functions are directly called from the
main module of the program in lines 35–
51.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 20
More on Functions
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 21
Calling Value-Returning Functions
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 22
Other examples of calls to value-returning functions.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 23
A value-returning function may return more than one value
by returning the values as a tuple.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 25
Element-wise Assignment
>>> (a, b) = (1, 2)
>>> c, d = 3, 4 // Tuple unpacking (extract values of a tuple back into individual variables)
>>> (c, d)
(3, 4) Tuple packing (group multiple
>>> a = b values into a tuple)
>>> b = a >>> a = 1,2,3
>>> a
>>> (a, b) (1, 2, 3)
(2, 2) >>> 1,2,3
>>> t = c (1, 2, 3)
>>> c = d
>>> d = t
>>> (c, d)
(4, 3)
>>> c, d = d, c
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 26
Let’s Try It
Enter the definitions of functions avg and minmax given above. Then
enter the following function calls and observe the results.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 27
Calling Non-Value-Returning Functions
displayWelcome()
welcome_displayed = displayWelcome()
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 28
Functions Designed to Take No Arguments
def fi():
return (3.14)
r = 10
print( fi() * 10 * 10)
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 29
Let’s Try It
Enter the definition of function hello given below, then enter the following
function calls and observe the results.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 30
Parameter Passing
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 31
The correspondence of actual arguments and formal parameters
is determined by the order of the arguments passed, and not
their names.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 32
The following parameter passing is perfectly valid.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 33
Let’s Try It
Enter the definition of function ordered given above into the Python Shell.
Then enter the following and observe the results.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 34
Mutable vs. Immutable Arguments
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 35
When literals are passed as arguments, there is no issue.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 36
Since function avg does not change the value of its parameters,
the corresponding actual parameters num1, num2 and num3 will
not be altered.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 37
Consider, however, the following function.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 38
What if the function call contained a variable as the argument, for
example, countDown(num_tics)?
If you try it, you will see that variable num_tics is left unchanged.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 39
Now consider the following function.
Function sumPos returns the sum of only the positive numbers in the provided argument
(list). It does this by first replacing all negative values in parameter nums with 0, then
summing the list using built-in function sum.
We see that the corresponding actual argument nums_1 has been altered in this case,
with all of the original negative values set to 0.
The reason that there was no change in integer argument num_tics but there was in
list argument nums_1 has to do with their types.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 40
Immutable Mutable
String Type
Tuples
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 41
num =10
k = num
Parameter passing of immutable; similar to k = 20
def foo(k) :
k = 20
foo(num)
def foo(k) :
k = 20
foo(num)
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 4.4 More on Python Lists 42
Parameter passing of mutable; similar to list1 = [1,2,3]
list2 = list1
def foo(list2) :
list2[0]=list2[0]+1
list1 = [1,2,3]
foo(list1)
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 4.4 More on Python Lists 43
Let’s Try It
Enter the following and observe the results.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 44
>>> def f(n, list1, list2):
... list1.append(3)
... list2 = [4, 5, 6]
... n = n + 1
...
>>> x = 5
>>> y = [1, 2]
>>> z = [4, 5]
>>> f(x, y, z)
>>> x, y, z
(5, [1, 2, 3], [4, 5])
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 45
Keyword Arguments in Python
The functions we have looked at so far were called with a
fixed number of positional arguments. A positional
argument is an argument that is assigned to a particular
parameter based on its position in the argument list,
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 46
Python provides the option of calling any function by the
use of keyword arguments. A keyword argument is an
argument that is specified by parameter name, rather than
as a positional argument.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 47
It is possible to call a function with the use of both
positional and keyword arguments. However, all positional
arguments must come before all keyword arguments in the
function call, as shown below.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 49
Default Arguments in Python
Python provides for default arguments. A default argument
is an argument that can be optionally provided.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 51
Variable Scope
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 52
Local Scope and Local Variables
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 53
Both func1 and func2 contain identifier n. Function func1 assigns n to 10,
while function func2 assigns n to 20. Both functions display the value of n
when called—func2 displays the value of n both before and after its call to
func1. If identifier n represents the same variable, then shouldn’t its value
change to 10 after the call to func1? The execution of func2, however, shows
that the value of n remains unchanged.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 54
Now consider the following.
In this case, when func2 is called, we get an error that variable n is not defined within
func1. This is because variable n defined in func2 is inaccessible from func1.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 55
Variable Lifetime
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 56
Let’s Try It
Enter the following function definition in the Python shell. Execute the
statements below and observe the results.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 57
Global Variables and Global Scope
Another reason that the use of global variables is bad practice is related to code reuse.
If a function is to be reused in another program, the function will not work properly if it is
reliant on the existence of global variables that are nonexistent in the new program
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 59
Let’s Apply It
GPA Calculation Program
The following program computes a semester GPA and new cumulative GPA
for a given student. This program utilizes the following programming
features:
➤ tuple assignment
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 60
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 61
Function convertGrade
(lines 3-7) s passed a letter
grade, and returns its
numerical value.
Function calculateGPA
(lines 24-41) is given a
current GPA (and number
credits based on), and
grades and credits for the
current semester, and
calculates both the current
semester GPA and new
cumulative GPA. (returned
as a tuple).
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 62
The program greeting is on
line 46. Lines 49–50 get
the number of earned
credits and current
cumulative GPA from the
user. These two variables
are bundled into a tuple
named cumm_gpa_info
on line 51 . Since they are
always used together,
bundling these variables
allows them to be passed
to functions as one
parameter rather than as
separate parameters.
Function getGrades is called on line 55 , which gets the semester grades from the user and assigns it to variable
semester_grades. On line 58 , function calculateGPA is called with arguments semester_grades and
cumm_gpa_info. Finally, the results are displayed on lines 61-62.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 63