lilian blot part v: functions core elements autumn 2013 tpop 1

34
Lilian Blot Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Upload: stanley-gooch

Post on 01-Apr-2015

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian BlotLilian Blot

PART V: FUNCTIONS

Core elements

Autumn 2013TPOP

1

Page 2: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Overview

Beyond the basic structure of a program

Why Function?

Void and Non-Void Function

Function: reading the small prints

Autumn 2013TPOP

2

Page 3: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Modularisation

Monolithic Programs cannot be maintained, nor reused easily

Decomposition of complex problem into smaller sub-problem

Modularisation Separation of concerns Semantically coherent

Autumn 2013TPOP

3

Page 4: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Why Function?

having similar code in two places has some drawbacks

failing to keep related part of the code in sync is a common problem in program maintenance

function can be used to reduce code duplication

Autumn 2013TPOP

4

Page 5: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Why Function?

make program more understandable

easier to maintain

easier to reuse

Autumn 2013TPOP

5

Page 6: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

In Summary

Advantages code reuse facilitate team work modularisation maintainability

monolithic code huge collection of statement

no modularisation no code reuse (cut & paste is not code reuse!) no parallel implementation

Autumn 2013TPOP

6

Page 7: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Functions

New Keywords def, return, global, None.

Function declaration and Function calls

Autumn 2013TPOP

7

Page 8: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

What is a Function?

math function f(x) = 2 * x +1

kind of a sub-program function definition when use, we say that the definition is ‘called’ or

‘invoked’

may or may not have argument

may or may not return a value/object

Autumn 2013TPOP

8

Page 9: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Void and non-void function

Void function doesn’t return anything (meaningful) help(…) function None keyword <type ‘NoneType’>

non-void function returns something other than None input(…) value raw_input(…) string int(…) int len(…) int

Autumn 2013TPOP

9

Page 10: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Declaring a Function

template:

def <function_name> (<formal_parameters>): <body>

<function_name>: an identifier <formal_parameters>: comma-separated identifiers <body>: any number of indented statements A non-void function must have a return statement as

the last statement of the <body>.

Autumn 2013TPOP

10

Page 11: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

non-void functions

Must have a return statement

Function with no parameter (see head_tail())

Function with one or more parameters (see norm(x,y))

Function returning multiple values (see to_polar(rho, angle))

Autumn 2013TPOP

11

Page 12: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Be Careful

print x, y never executed

In some language this would be a compile error

Autumn 2013TPOP

12

def f(x): y = 3 * x + 7 return y print x, y

Code

Page 13: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Void function

Aimed at changing a state or display information

No return statement

Technically, all function return something

A void function will return the None value even if there is no return statement in the body

Autumn 2013TPOP

13

Page 14: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Call

When Python comes to a function call, it initiate a four-step process:

1. the calling program suspends execution at the point of call

2. the formal parameter of the function get assigned the value supplied by the actual parameters in the call

3. the body of the function is executed

4. control returns to the point just after where the function was called

Autumn 2013TPOP

14

Page 15: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot Autumn 2013TPOP

15

def head_tail():rand = random.random()if(rand < 0.5):

return 'head'else :

return 'tail'

Code

>>> heads = 0>>> tails = 0>>> for i in range(1, 10000):

if (head_tail() == 'head'):heads += 1

else :tails += 1

>>>

Interpreter

Page 16: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Passing Parameters

Code in Python interpreter

Autumn 2013TPOP

16

Page 17: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Passing Parameters

t

Autumn 2013TPOP

17

account

rate

my_account

bank_rate

100.0

0.07

107.0

def addInterestOne(account, rate): account = account * (1+rate)

my_account = 100.0bank_rate = 0.07addInterestOne(my_account, bank_rate)print "new accounts balance:", my_account

Code

Page 18: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Passing Parameters

t

Autumn 2013TPOP

18

accounts

rate

lst_account

bank_rate0.07

def addInterestAll(accounts, rate): for account in range(len(accounts)): accounts[account] *= (1+rate)

lst_accounts = [10, 20, 100]bank_rate = 0.07addInterestAll(lst_accounts, bank_rate)print "new accounts balance:", lst_account

Code

0 1 2

10 20 10010.7 21.4 107

account0

1

2

Page 19: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Passing Parameters

t

Autumn 2013TPOP

19

account

rate

my_account

bank_rate

100.0

0.07

107.0

def addInterestOne(account, rate): account = account * (1+rate) return account

my_account = 100.0bank_rate = 0.07my_account = addInterestOne(my_account, bank_rate)print "new accounts balance:", my_account

Code

Page 20: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Function Design Concepts

Use arguments for inputs and return for outputs

Use global variables only when absolutely necessary

Do NOT change mutable arguments unless the caller expect it

Autumn 2013TPOP

20

Page 21: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian BlotLilian Blot

THE SMALL PRINTS

Functions

Autumn 2013TPOP

21

Page 22: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Variable Scope

Code in Python interpreter

Autumn 2013TPOP

22

Page 23: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Namespace

In order to avoid clashes between names (variables) inside the function and outside the function, function define a nested namespace

Functions define local scopes Modules define global scopes Each call to a function is a new local scope Assigned names in a function are local, unless

declared global Names not assigned a value in the definition function

are assumed to be global

Autumn 2013TPOP

23

Page 24: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Namespace & Variable Scope

Python’s three scopes

Autumn 2013TPOP

24

Built-in• predefined names: len, max, …

Global (module)• Names assigned at top level of a module• Names declared “global” in function

Local (function)• Names assigned inside a function

def

Page 25: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Name Resolution: LGB rule

Name/variable references search at most 3 scopes:

Local Global Built-in

Autumn 2013TPOP

25

Page 26: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Name Resolution: LGB rule

When you use an unqualified name inside a function, Python searches the local (L), then the global (G), and then the built-in (B) scopes and stop at the first place the name is found

see change_global1(x) and change_global2(x) in python_scope.py

Autumn 2013TPOP

26

Page 27: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Name Resolution: LGB rule

When you assign a name in a function (e.g. result = 1.0), Python always creates or change the name in the local scope, unless it’s declared to be global in that function.

see change_global4(x) and change_global3(x) in python_scope.py

Autumn 2013TPOP

27

Page 28: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Name Resolution: LGB rule

When outside a function, the local scope is the same as the global, e.g. the module’s namespace.

Autumn 2013TPOP

28

Page 29: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Name Resolution: LGB rule

To summarise:

Global names are ??? Local names are ???

Autumn 2013TPOP

29

x, y, v = 1, 3, 7

def the_global_thing(z): global u v = 5 u = x + y * (z – v)

Code

Page 30: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Summary

Parameter passing Immutable object passed by value Mutable object passed by reference

Namespace and scopes Three scopes Local Global Built-in

Autumn 2013TPOP

30

Page 31: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Reading

Python Code Style, Comments and DocString http://www.python.org/dev/peps/pep-0008/ http://www.python.org/dev/peps/pep-0257/

Must be applied to your code!!!

Autumn 2013TPOP

31

Page 32: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

More on Function

Warning

You do not need to know or understand this right now. You may not even use it this year

READ the following slide ONLY if you are confident with what we have seen so far on

function

Autumn 2013TPOP

32

Page 33: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Special Argument-Matching Modes

Positional: matched left to right What we have seen so far

Keywords: matched by argument name

Autumn 2013TPOP

33

def my_func(name, age = 18, nationality = ‘French’): print name, age, nationality

my_func(‘Lilian Blot’, age = 21)my_func(name = ‘toto’, nationality = ‘UK’)my_func(‘titi’, 5, ‘US’)my_func(‘nono’, 30)

Code

Page 34: Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1

Lilian Blot

Special Argument-Matching Modes

Defaults: specify values for arguments that are not passed

varargs: catch unmatched positional or keyword arguments

Autumn 2013TPOP

34

def my_args_func(*args): #unmatched positional argument print args

def my_args2_func(**args): # unmatched keyword argument print args

Code