ics1133 natural language programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ics1133/python_3.pdf ·...

26
Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133 Natural Language Programming Python III Mike Rosner, Dept ICS February 2012 Python III LIII Natural Language Programming 1/ 26

Upload: letuyen

Post on 09-Mar-2018

220 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

ICS1133 Natural Language Programming

Python III

Mike Rosner, Dept ICSFebruary 2012

Python III LIII Natural Language Programming 1/ 26

Page 2: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Contents

1 FunctionsWhat is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

2 Parameters and ArgumentsFormal and Actual Parameters

3 Returning Values

4 Extent of Local Variables

Python III LIII Natural Language Programming 2/ 26

Page 3: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Functions: two views

We can think of a function in two ways:

As a mathematical object. Here we mean something appliedto an argument that yields a value. An example is the squareroot function which applies to a numerical argument in orderto yield a numerical result e.g.

√4 = 2. In a programming

language we will typically write this with ascii characters i.e.sqrt(4).

As shorthand. Very often we use a repeated sequence ofstatements over and over again. We can associate thissequence of statements with a single function name.

Python III LIII Natural Language Programming 3/ 26

Page 4: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Functions

A function is a named sequence of statements that performs acomputation.

Two important aspects of functions are:

Function definitionFunction invocation (or function call).A function call usually returns a result value.

Example of function call

>>> type(123)<type ’int’>

type is the function name

123 is the argument

<type ’int’> is the result value

Python III LIII Natural Language Programming 4/ 26

Page 5: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Conversion Functions

A very common kind of function converts a value from onetype to another

For example, int converts its argument to an integer, if thatis possible

>>> int(’32’)32>>> int(’foo’)Error: invalid literal

str does the inverse

>>> int(32)’32’

Python III LIII Natural Language Programming 5/ 26

Page 6: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Maths Functions and Modules

Python has an extensive set of mathematical functions. Theseare usually hidden.

They are kept in a separate module called the “math” module.

In order to access functions inside a module you first have to“import” the module.

Once imported the name of the module should be pre-pendedto the name of the function.

So for example one can access the sqrt function as follows:

>>> import math>>> math.sqrt(4)2.0

If you forget to import the module the function is undefinedand you get an error.

Note the type conversion that is taking place automatically

Python III LIII Natural Language Programming 6/ 26

Page 7: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Function Composition

When a function is called, the argument can be

A value.

>>> float(4)4.0

A variable

>>> x =float(4)>>> math.sqrt(x)2.0

An expression

>>> x = math.sin(degrees / 360.0 * 2 * math.pi)

A function call

>>> x = math.exp(math.log(x+1))

Almost anywhere you can put a value, you can put anarbitrary expression

Python III LIII Natural Language Programming 7/ 26

Page 8: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Function Definition

So far, we have only been using the functions that come withPython, but it is also possible to add new functions.

A function definition specifies the name of a new functionand the sequence of statements that execute when thefunction is called.

def print_lyrics():print "I’m a lumberjack, and I’m okay."print "I sleep all night and I work all day."

def is a keyword that indicates that this is a functiondefinition.

The name of the function is print_lyrics.

The rules for function names are the same as for variablenames

Python III LIII Natural Language Programming 8/ 26

Page 9: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Class Exercise 3.1

Try defining print-lyrics in interactive mode.

def print_lyrics():print "I’m a lumberjack, and I’m okay."print "I sleep all night and I work all day."

Note that in interactive mode Python uses . . . to tell you thatdefinition is not completeTo end the function you need to enter a blank line.Once the function is defined the function name has a value

>>> print_lyrics<type ’function’>

And the function can be called

>>> print_lyrics()I’m a lumberjack, and I’m okay.I sleep all night and I work all day.

Python III LIII Natural Language Programming 9/ 26

Page 10: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Indentation

Python uses indentation to show block structure.Indent one level to show the beginning of a block; outdent onelevel to show the end of a block.The convention is to use four spaces (and no hard tabs) foreach level of indentation

This is much less wordy than the C-Style of writing

C-Style Python Styleif (x) if x:{ if y:

if (y) f1(){ f2()

f1()}f2()

}Python III LIII Natural Language Programming 10/ 26

Page 11: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Indentation

def print_lyrics():print "I’m a lumberjack, and I’m okay."print "I sleep all night and I work all day."

A function definition consists of two parts: the header,terminated by the colon, which contains the name and otherinformation, and the body which contains the statements tobe executed.

The body forms a separate “block”

In Python, each line in a block must be indented

When you indent the lines in a block, make sure each linebegins with the same number of spaces.

You can use either tabs or spaces when indenting tabs in ablock, but don’t use both.

Python III LIII Natural Language Programming 11/ 26

Page 12: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Using Functions

Once a function is defined it can also be used inside thedefinition of other functions

def print_lyrics():print "I’m a lumberjack, and I’m okay."print "I sleep all night and I work all day."

def repeat_lyrics():print_lyrics()print_lyrics()

repeat_lyrics()

Python III LIII Natural Language Programming 12/ 26

Page 13: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Exercise 3.2

Figure out how to run this program using idle.

In particular use the edit window and make use ofcheck-module and run-module

Move the last line of this program to the top, so the functioncall appears before the definitions. Run the program. Whathappens?

Move the function call back to the bottom and move thedefinition of print lyrics after the definition ofrepeat lyrics. What happens?

Python III LIII Natural Language Programming 13/ 26

Page 14: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

What is a function?Examples of FunctionsMath functions - use of modulesDefining Functions

Flow of Execution

Execution always begins at the first statement of the program.

Statements are executed one at a time, in order from top tobottom.

A function definitions does not alter the flow of execution ofthe program.

But a function call is like a detour. Instead of going to thenext statement, the flow jumps to the body of the function,executes all the statements there, and then comes back topick up where it left off.

When you read a program, you don’t always want to readfrom top to bottom. Sometimes it makes more sense to followthe flow of execution.

Python III LIII Natural Language Programming 14/ 26

Page 15: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Formal and Actual Parameters

Parameters and Arguments

Some functions, , such as print twice, require arguments

def print_twice(bruce):print bruceprint bruce

When the function is called, it prints the value of theargument (whatever it is) twice.

>>> print_twice(’Spam ’*4)Spam Spam Spam SpamSpam Spam Spam Spam>>> print_twice(math.cos(math.pi))-1.0-1.0

Python III LIII Natural Language Programming 15/ 26

Page 16: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Formal and Actual Parameters

Parameters and Arguments

You can also use a variable as an argument in a call:

>>> michael = ’Eric, the half a bee.’>>> print_twice(michael)Eric, the half a bee.Eric, the half a bee.

Notice what is happening here: when the function is called,first the argument is evaluated to yield a value.

The value is then passed to the function.

Python III LIII Natural Language Programming 16/ 26

Page 17: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Formal and Actual Parameters

Formal and Actual Parameters

The variables appearing in the first line of a definition (suchas bruce below) are called formal parameters.

def print twice(bruce):print bruceprint bruce

Formal parameters are just a place holders for the values thatare passed to the function.

When a function is called, the argument is called an actualparameter, as shown in red below:twice(michael)

In Python, when the call takes place, the actual parameter isevaluated just once - (in this case to yield the string ’Eric, thehalf a bee’)

Python III LIII Natural Language Programming 17/ 26

Page 18: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Formal and Actual Parameters

Formal and Actual Parameters

That value is then passed to the function and assigned to theformal parameter.

The body of the function is then executed, and for eachoccurrence of the formal parameter, the passed value issubstituted i.e.

print ’Eric, the half a bee’print ’Eric, the half a bee’

Python III LIII Natural Language Programming 18/ 26

Page 19: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Exercise 3.3

1 Write a function named right justify that takes a stringnamed s as a parameter and prints the string with enoughleading spaces so that the last letter of the string is in column70 of the display. N.B. You will need to use the built-infunction called len that returns the length of a string.

2 What is the value returned by right justify?

3 What is the type of the value returned byright justify(’hello’)?

4 Write a function double which doubles its argument.

5 What is the type of the value returned by double(4)?

Python III LIII Natural Language Programming 19/ 26

Page 20: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Returning a Value

Unlike mathematical functions, the functions we have seen sofar simply carry out actions and do not return any value.

However, we often do want to return a value.

It would be nice to write

>>> x = double(4)

and have x take the value 8.

This can be achieved with the return statement

Within a function body, the statementreturn expressionimmediately terminates the function and causes it to returnthe value of the expression, e.g.

def double(n):return n*2

Python III LIII Natural Language Programming 20/ 26

Page 21: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Class Exercise 3.4

1 Redefine double and show that>>> x = double(2)really does change the value of x

2 Write a function type-token which takes the name of a text(in nltk) and determines the token:type ratio. You will needto divide the length of the text by the length of thevocabulary. You can get the vocabulary by turning the stringinto a set.

3 Write a function type-token-right which prints thetype:token ratios of all the nltk texts right justified.

Python III LIII Natural Language Programming 21/ 26

Page 22: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Local Variables

Functions contain local variables as shown in blue below:

def type-token(text):ntokens = len(text))types = set(text))ntypes = len(set(text)))return ntokens/ntypes

Local variables include formal parameters and those createdby assignment.

Local variables exist only during the function invocation.

When the function terminates, local variables no longer exist.

The “extent” of the variable is the function invocation.

Python III LIII Natural Language Programming 22/ 26

Page 23: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Local Variables Example

def cat_twice(part1, part2):cat = part1 + part2print_twice(cat)

>>> line1 = ’Bing tiddle ’>>> line2 = ’tiddle bang.’>>> cat_twice(line1, line2)Bing tiddle tiddle bang.Bing tiddle tiddle bang.>>>print catNameError: name ’cat’ is not defined

Python III LIII Natural Language Programming 23/ 26

Page 24: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Stack Diagram

line1

line2 ’tiddle bang.’

part1

part2

cat

bruce

’Bing tiddle ’

’Bing tiddle ’

’tiddle bang.’

’Bing tiddle tiddle bang.’

’Bing tiddle tiddle bang.’

__main__

cat_twice

print_twice

Python III LIII Natural Language Programming 24/ 26

Page 25: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Stack Frames

Local variables are kept in “stack-frames”.

Whenever a function is invoked, a new stack-frame (grey box)is pushed onto the bottom of the stack.

Thus, reading top to bottom one sees the order in whichfunctions have been called.

When the function finishes, the stack-frame goes away – andso do the variables contained in it.

Python III LIII Natural Language Programming 25/ 26

Page 26: ICS1133 Natural Language Programming - staff.um.edu.mtstaff.um.edu.mt/mros1/ICS1133/python_3.pdf · Functions Parameters and Arguments Returning Values Extent of Local Variables ICS1133

FunctionsParameters and Arguments

Returning ValuesExtent of Local Variables

Summary

Functions

Mathematical definitionAs a collection of statements

Importing functions from modules. Prefix notation formodules.

Different forms of arguments in a function call.

Function Definitions;

Indentation of blocksFormal and actual ParametersReturning values

Extent of local variables: stack diagram

Python III LIII Natural Language Programming 26/ 26