Class 23 — Friday October 16
Form with function
The task before us — Turn the abstract to concrete – Functions are at hand
Being functional — Is your mantra from now on — Embrace to your core
Look both ways
Agenda
- Start function-based chrestomathics
Examples
- Module harb.py
- Program inger.py
- Module olio.py
- Program use_olio.py
To do
- Look over artifacts (f any)
- Look at Hands on Python
- Look at function epistle
Slides
- Slide show available at bottom of this page.
Program wc.py — proves my point about importance of functions
''' Purpose: determine number of lines, words, and characters in a user-specified
web file.
'''
# import module for internet access
import url
# get the lines of text from a user-specified file
reply = input( 'Enter web file link: ' )
link = reply.strip()
contents = url.get_contents( link )
# count the number of lines, words, and characters in the contents
nbr_lines = contents.count( '\n' )
words = contents.split()
nbr_words = len( words )
nbc_chars = len( contents )
# display result
print( 'nl =', nbr_lines )
print( 'nw =', nbr_words )
print( 'nc =', nbc_chars )
Here we go
- Question: Why bother with functions?
- Makes problem solving possible. Without them you would need to figure out
- How to communicate with your keyboard to read what it’s being typed
- How to communicate to your display so that information can be displayed
- How to specify the range of integers a
for
statement uses to loop.
- How to ...
- Question: What built-in functions are missing — how should Python be updated?
- The
url.py
module is an attempt by me to let you skip the tedious web processing setup to do something interesting
- One of your classmates asked whether there was some function
ints()
that would handle a string containing a bunch of integers.
- We will get to that likely the end of next week.
You are already experienced with functions and modules (e.g,, wc.py
)
- Used built-in functions
- Used string and list manipulating functions
- Imported standard modules and then made use of their functions
- Imported url.py and then made use of its functions
Module harb.py
Function
add()
- Has two parameters
a
andb
. Returns the value of a + b
- If the following code segment from program
inger.py
is executed
import harb
n1, n2 = 3, 14
n3, n4 = 15, 92
t1 = harb.add( n1, n2 )
t2 = harb.add( n3, n4 )
print( "add(", n1, ",", n2, "):", t1 )
print( "add(", n3, ",", n4, "):", t2 )
then the output should be
add( 3 , 14 ): 17
add( 15 , 92 ): 107
Function
negate( x )
- Has one integer parameter
x
. Returns the additive inverse ofx
; i.e,-x
n5, n6 = -6, 53
i1 = harb.negate( n5 )
i2 = harb.negate( n6 )
print( "negate(", n5, "):", i1 )
print( "negate(", n6, "):", i2 )
then the output should be
negate( -6 ): 6
negate( 53 ): -53
Modules
-
A module is a named collection of functions
- Module name required to be a legal identifier
- The functions of a module are stored in a Python file (
.py
) that matches the module name
- All modules we develop will be kept in your CS 1112 class folder
- Access to a module capabilities is via importing
import harb
...
Functions
-
A function is a named block of code to carry out some specific task
- Function name required to be a legal identifier (just like variables are)
- Functions can have special variables called parameters to store start up values
- Access to a module capabilities is via invocation
module_name . function_name ( arguments )
- The module_name is the name of the
.py
file containing the definition of function_name().
- The function_name is the name of the function being invoked.
- The module and function names must be identifiers.
- Operator
.
is the selection operator. The operator indicates that a component of the indicated module is to be accessed.
- The arguments are a list of start up values copied/passed to the function so that it can carry out its task.
- The arguments are used to initialize the parameters of the function.
- For example, the below code segment twice invokes module
harb
functionadd()
.
t1 = harb.add( n1, n2 )
t2 = harb.add( n3, n4 )
- The first invocation passes the values of
n1
andn2
toadd()
to use as the start up values respectively for its parametersa
andb
.
- The second invocation passes the values of
n3
andn4
toadd()
to use as the start up values respectively for its parametersa
andb
.
- Functions can produce information that is handed back via a return statement
return return expression
- For functions that end without return statements, Python supplies the value
None
Function syntax
- A function definition looks like the following
def function_name( parameters ) :
''' header_comment
'''
action
- The keyword
def
signals that a function is being defined
- The function_name is an identifier that names the task
- The parameters are a parenthesized list of variable names (identifiers)
- The function_name along with the parameters form the function header
- The colon
:
is a separator of the function header from the function and its action
- The header comment (docstring) describes the function
- The action is a non-empty block of statements that run when the function is invoked
- For example, the definition of function
add()
from moduleharb.py
is
def add( a, b ) : # function named add(), parameters named a and b
''' Returns value of a + b
'''
result = a + b # compute value of interest
return result # function hands back its result
Function invocation
- Checks whether the number of arguments in the invocation and parameters in the definition match
- No match: an execution error occurs
- Match: arguments are evaluated (values are determined)
t1 = harb.add( n1, n2 ) # good: correct number of arguments
t2 = harb.add( n3, n4 ) # good: correct number of arguments
t3 = harb.add( ) # bad: too few arguments
t4 = harb.add( n1, n2, n3, n4 ) # bad: too many arguments
- Sets aside some computer memory for carrying out the function
- That memory is called an activation record or a frame
- Stores values of the parameter variables
- The parameter variables are initialized with the argument evaluations
- Stores the values of other variables needed to perform its task
def add( a, b ) : # function named add(), parameters named a and b
''' Returns value of a + b
'''
result = a + b # compute value of interest
return result # function hands back its result
- The function’s code runs; i.e., it has the flow of control
- Function completition process
- A function completes as soon as it reaches a
return
statement or when it finished executing all of the code of the function, whatever happens first.
- When the function completes, the flow of control goes back to the code that did the invocation, and it is that code now continues being executed
- If a
return
statement is reached, the return value is determined
- If there is an expression following keyword return, its value is the return value
- If there is no expression following keyword return, the return value is
None
- If the code complete without reaching a
return
statement,
- The return value is set
None
- Once the return value is set, the execution of the function immediately stops and
- The flow of control goes back to the statement that did the invocation
- The value of the invocation – its evaluation – is the return value
Taxonomy
- The two main kinds of functions are
- Functions that have parameters and return values
- Functions that have parameters and have
None
as the return value
- There can also be
- Functions that do not have parameters, but do return values
- Functions that do not have parameters and have
None
as the return value
Implementing functions
- When designing a function we need to
- Determine what information is needed upon startup
- Determine what information is to be produced
- Provide an algorithm for going from one to the other
What's next
- Look at Hands on Python
- Two www.python.org resources should be examined now and also re-examined later.
- The Python Tutorial includes a section on functions. I recommend before going there to thoroughly review the discussion presented here.
- Python enhancement proposal 008 (PEP 008) includes recommended practices for naming modules, functions, and variables. The recommendations suggest that function and variable names are as a rule written in _snakecase; that is, lower-case words joined by underscores. Module names are expected to be short, lower-case, and no separation between words. I will add that function names are often action or verb phrases; e.g.,
input_integer()
.
Slide show
© 2020 Jim Cohoon | Resources from previous semesters are available. |