Class 24 — Wednesday March 31
Form with function
The task before us — Turn the abstract to concrete – Functions are at hand
Look both ways
Agenda
- Start function-based chrestomathics
Examples
- Program wc.py
- Module harb.py
- Program inger.py
- Module olio.py
- Program use_olio.py
Proving my point about importance of functions
# 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 )
Module harb.py
Function
add()
- Has two parameters
a
andb
. Returns the value of a + b
Function
negate( x )
- Has one integer parameter
x
. Returns the additive inverse ofx
; i.e,-x
To do
- Look over artifacts
- Look at Hands on Python
- Look at function epistle
- Also worthwhile to look at the other epistles. Some others were also added.
Module
Slides
- Slide show available at bottom of this page.
Where we left off
- 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: Why bother with non-standard functions?
- Tasks important to you can be solved and reused as wanted
- Module
url.py
lets us skip tedious web processing setup to do something interesting
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
Module olio.py
Function voting_age()
- Does not take any parameters. Returns an integer indicating how old you need to be to vote. For example, the following code segment initializes both x and y to the integer
18
.
x = olio.voting_age()
y = olio.voting_age()
Function has_blanks( s )
- Has one parameter
s
. Returns whethers
contains at least one blank character; i.e., returnsTrue
ifs
contains a blank, and returnsFalse
otherwise. For example, the following code segment initializesb1
andb2
toTrue
andFalse
respectively.
x = 'CS 1112'
y = 'the_aarvark_said_arf_arf'
b1 = olio.has_blanks( x )
b2 = olio.has_blanks( y )
Function great_seal()
- Does not have any parameters and does not return a value. The function prints text from the Great Seal of the United States, i.e., E Pluribus Unum.
- The code segment
olio.great_seal( )
print()
olio.great_seal( )
print()
produces as output
E Pluribus Unum
E Pluribus Unum
Function a_ing( n )
- Has one parameter
n
. The function does not perform a return, instead it printsn
lines of output. The first line prints a single'a'
, the second line prints'aa'
, the third line prints'aaa'
, and so on. The string operator*
should prove useful. For example usage, the code segment
olio.a_ing( 5 )
print()
olio.a_ing( 1 )
print()
olio.a_ing( 3 )
produces as output
a
aa
aaa
aaaa
aaaaa
a
a
aa
aaa
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
🦆 © 2022 Jim Cohoon | Resources from previous semesters are available. |