0% found this document useful (0 votes)
7 views63 pages

CH 05

Chapter 5 discusses the importance of functions in Python programming, emphasizing their role in managing complexity by breaking programs into manageable pieces. Functions allow for abstraction, code reuse, and easier testing, with both value-returning and non-value-returning types. The chapter also covers defining functions, parameter passing, and the implications of mutable vs. immutable arguments.

Uploaded by

김우석
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views63 pages

CH 05

Chapter 5 discusses the importance of functions in Python programming, emphasizing their role in managing complexity by breaking programs into manageable pieces. Functions allow for abstraction, code reuse, and easier testing, with both value-returning and non-value-returning types. The chapter also covers defining functions, parameter passing, and the implications of mutable vs. immutable arguments.

Uploaded by

김우석
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Chapter 5 Functions

A program as a single series of statements, vs.

A program as groups of statements called functions, each of which accomplishes a specific task

Functions in Python are fundamental building blocks in program.

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.

In theory, these are the only statements needed to write any


program. From a practical point-of-view, however, these
alone are not enough.

The problem is complexity. Some smart phones, for example,


contain over 10 million lines of code.

If those 10 million lines are in a single code piece as we did


so far, we cannot “control” (유지, 보수, 관리) the complexity
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 2
Measures of Lines of Program Code

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)

Statements Statements Function Foo()


Foo() Statements
Statements
Vs.
Statements Statements
Function Boo()
Statements Boo() Statements
Statements Goo()
Function Goo()
Statements Foo() Statements
Statements

...

Doing so is a form of abstraction such that we want to hide


complex details of a function with its name.
Also, functions provide the opportunity for code reuse, so
that systems do not have to be created from scratch.

We look at the definition and use of functions in Python.


Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 4
Python Functions

We have already been using Python’s built-in functions such


as len, range, input, print, and others.

We now look more closely at how functions are used in


Python, as well as how to define our own.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 5
What is a Function (Routine)?

A function is a named group of statements performing


some task. Function A()
stmt1

while ( … ) :

stmt1

stmt2

A function can be invoked (called) as many times as needed


in a given program

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 6
Function A()
stmt1

. while (…) :

Call to Function A stmt1


. stmt2
.

Call to Function A Function B()


. stmt1
.
while (…) :
Call to Function B
. stmt1
. stmt2

When a function terminates, execution automatically returns


to the point from which it was called.

Some functions are predefined in the programming language,


and others are designed and implemented by the programmer.

So far, we can say we had a single function, which we call main()


Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 7
Information Hiding with Function
Function call analogy:
• Boss asks worker to complete task
• Worker gets information, does task, returns result
• Information hiding: boss does not know details
Hierarchical boss function/worker function relationship.
main

worker1 worker2 worker3

worker4 worker5

Simplifies program design


• OO Languages (e.g., C++, Java) extends information hiding
further beyond functions
Benefits of Functions
• Abstraction
– Information hiding
• Divide and conquer
– Manageable program development, easier to test
• Software reusability
– Use existing functions (e.g., library functions) as building
blocks
• Other benefits
– Avoid code repetition, centralize changes, avoid typing
errors
Defining Functions

• A function header starts with the keyword def, followed by an identifier


(avg), which is the function’s name.

• The function name is followed by a comma-separated (possibly empty) series


of identifiers (n1, n2, n3) called formal parameters, or simply
“parameters.” Following the parameter list is a colon ( : ).

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

Functions are generally defined at the top of a program. However, every


function just needs to be defined before it is called.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 11
Value-Returning Functions

A value-returning function is a program routine called for its return value,


and is therefore similar to a mathematical function, e.g.,

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

Program functions are similarly used.

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,

result = avg(10, 25, 16) * factor

• A call to a non-value-returning function is a statement. Thus, calls to


non-value-returning functions are written as a statement (instruction) on
its own,
displayWelcome()

• Technically, all functions in Python are value-returning, since functions


that do not return a value return special value None.

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

The following is a program that allows a user to convert a range of values


from Fahrenheit to Celsius, or Celsius to Fahrenheit, as presented in Chapter
3. In this version, however, the program is designed with the use of
functions. This program utilizes the following programming features.

➤ value-returning functions ➤ non-value-returning functions

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.

Two non-value-returning functions are


defined, used to display converted
temperatures:
displayFahrenToCelsius (line 17)
and displayCelsiusToFahren
(line 26). Each is passed two arguments,
temp_start and temp_end, which
indicate the range of temperature values
to be converted.

Note that (value-returning) function


getConvertTo (line 9) does not take
any arguments. This is because the value
returned strictly depends on input from
the user.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.1 Program Routines 20
More on Functions

We further discuss issues related to function use, including


more on function invocation and parameter passing.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 21
Calling Value-Returning Functions

Calls to value-returning functions can be used anywhere that


a function’s return value is appropriate,

result = max(num_list) * 100

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.

(a) Expressions containing multiple function calls


(b) Function call as an argument to another function call
(c) Function call as conditional expression
(d) Function call as part of calls to built-in print function

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.

(a) Assigns the returned tuple to the variable highlow_temps


(b) Uses tuple assignment to assign both variables high and low
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 24
Element-wise Assignment 1
>>> [a, b] = [1, 2]
>>> [c, d] = 3, 4
>>> [e, f] = (5, 6)
>>> (g, h) = 7, 8
>>> i, j = [9, 10]
>>> k, l = (11, 12)
>>> a
1
>>> [b, c, d]
[2, 3, 4]
>>> (e, f, g)
(5, 6, 7)

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

Calls to non-value-returning functions are for the side-


effects produced, and not for a returned function value,
such as displaying output on the screen,

displayWelcome()

It does not make sense to treat this function call as an


expression,

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

Both value-returning and non-value-returning functions can be


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

Parameter passing is the process of passing arguments to a


function.

Recall that actual arguments are the values passed to a


function’s formal parameters to be operated on.

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.

It is fine to pass actual arguments num1 and num2 to function


ordered as shown (either num1 as the first argument, or num2 as
the first)

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

There is an issue related to parameter passing not yet considered.

If a function changes the value of any of its formal parameters,


does that change the value of the corresponding actual argument
passed?

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.

It is when the actual arguments are variables that this must be


considered.

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.

This function simply displays a countdown of the provided integer


parameter value. For example, function call countDown(4)
produces the following output,

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

Since function countDown alters the value of formal parameter n,


decrementing it until it reaches the value − 1, does the
corresponding actual argument num_tics have value − 1 as well?

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

Numeric Types Lists


(integers and floats)
Dictionaries
Boolean Type (not yet introduced)

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.

>>> def foo(x):


x = x + '!'
print(x)
>>> y = 'ab'
>>> foo(y)
ab!
>>> y
'ab'

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.

This can be a useful way of calling a function if it is easier


to remember the parameter names than it is to remember
their order.

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.

This form of function call might be useful, for example, if


you remember that the first argument is the loan amount,
but you are not sure of the order of the last two arguments
rate and term.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 48
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 49
Default Arguments in Python
Python provides for default arguments. A default argument
is an argument that can be optionally provided.

Parameter term is assigned a default value, 20, and


therefore is optionally provided when calling function
mortgage_rate. All positional arguments must come
before any default arguments in a function definition.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 50
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 51
Variable Scope

Variable scope has to do with the parts a program that a given


variable is accessible.

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

A local variable is a variable that is only accessible from within a


given function. Such variables are said to have local scope. In
Python, any variable assigned a value in a function becomes a
local variable of the function.

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

The period of time that a variable exists is called its lifetime.


Local variables are automatically created (allocated memory)
when a function is called, and destroyed (de-allocated) when the
function terminates. Thus, the lifetime of a local variable is equal
to the duration of its function’s execution. Consequently, the
values of local variables are not retained from one function call
to the next.

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

A global variable is a variable that is defined outside of any


function definition. Such variables are said to have global scope.
Their value can be read inside any function.
If a variable is assigned a new value anywhere within the
function's body, it is regarded to be a local.
>>> def foo(): >>> goo()
print(n) >>> foo()
>>> def goo(): 1
n = 10 >>> n
>>> n = 1 1
>>> foo()
1
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 5.2 More on Functions 58
Variable max is defined outside func1 and func2, and therefore “global” to each. Thus, it
is referred to as a global variable. As a result, it is directly accessible by both functions.

The use of global variables is generally considered to be bad programming style.


Although it provides a convenient way to share values among functions, all functions
within the scope of a global variable can access and alter it. This may include functions
that have no need to access the variable, but none-the-less may unintentionally alter it.

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 getGrades (lines


9-12) gets the semester
grades from the user. It
returns a list of sublists.
Each containing a letter
grade and the number of
credits, [['A', 3], ['B', 4], ['A',
3], ['C', 3]].
return semester_info

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

You might also like