Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1."— Presentation transcript:

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

2 Lilian Blot Overview Beyond the basic structure of a program Why Function? Void and Non-Void Function Function: reading the small prints Autumn 2013 TPOP 2

3 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 2013 TPOP 3

4 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 2013 TPOP 4

5 Lilian Blot Why Function? make program more understandable easier to maintain easier to reuse Autumn 2013 TPOP 5

6 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 2013 TPOP 6

7 Lilian Blot Functions New Keywords  def,  return,  global,  None. Function declaration and Function calls Autumn 2013 TPOP 7

8 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 2013 TPOP 8

9 Lilian Blot Void and non-void function Void function doesn’t return anything (meaningful)  help(…) function  None keyword non-void function returns something other than None  input(…)  value  raw_input(…)  string  int(…)  int  len(…)  int Autumn 2013 TPOP 9

10 Lilian Blot Declaring a Function template: def ( ):  : an identifier  : comma-separated identifiers  : any number of indented statements  A non-void function must have a return statement as the last statement of the. Autumn 2013 TPOP 10

11 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 2013 TPOP 11

12 Lilian Blot Be Careful print x, y never executed In some language this would be a compile error Autumn 2013 TPOP 12 def f(x): y = 3 * x + 7 return y print x, y Code

13 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 2013 TPOP 13

14 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 2013 TPOP 14

15 Lilian Blot Autumn 2013 TPOP 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

16 Lilian Blot Passing Parameters Code in Python interpreter Autumn 2013 TPOP 16

17 Lilian Blot Passing Parameters t Autumn 2013 TPOP 17 account rate my_account bank_rate 100.0 0.07 107.0 def addInterestOne(account, rate): account = account * (1+rate) my_account = 100.0 bank_rate = 0.07 addInterestOne(my_account, bank_rate) print "new accounts balance:", my_account Code

18 Lilian Blot Passing Parameters t Autumn 2013 TPOP 18 accounts rate lst_account bank_rate 0.07 def addInterestAll(accounts, rate): for account in range(len(accounts)): accounts[account] *= (1+rate) lst_accounts = [10, 20, 100] bank_rate = 0.07 addInterestAll(lst_accounts, bank_rate) print "new accounts balance:", lst_account Code 0 1 2 1020100 10.7 21.4107 account 0 1 2

19 Lilian Blot Passing Parameters t Autumn 2013 TPOP 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.0 bank_rate = 0.07 my_account = addInterestOne(my_account, bank_rate) print "new accounts balance:", my_account Code

20 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 2013 TPOP 20

21 Lilian Blot THE SMALL PRINTS Functions Autumn 2013 TPOP 21

22 Lilian Blot Variable Scope Code in Python interpreter Autumn 2013 TPOP 22

23 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 2013 TPOP 23

24 Lilian Blot Namespace & Variable Scope Python’s three scopes Autumn 2013 TPOP 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

25 Lilian Blot Name Resolution: LGB rule Name/variable references search at most 3 scopes:  Local  Global  Built-in Autumn 2013 TPOP 25

26 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 2013 TPOP 26

27 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 2013 TPOP 27

28 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 2013 TPOP 28

29 Lilian Blot Name Resolution: LGB rule To summarise:  Global names are ???  Local names are ??? Autumn 2013 TPOP 29 x, y, v = 1, 3, 7 def the_global_thing(z): global u v = 5 u = x + y * (z – v) Code

30 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 2013 TPOP 30

31 Lilian Blot Reading Python Code Style, Comments and DocString  http://www.python.org/dev/peps/pep-0008/ http://www.python.org/dev/peps/pep-0008/  http://www.python.org/dev/peps/pep-0257/ http://www.python.org/dev/peps/pep-0257/ Must be applied to your code!!! Autumn 2013 TPOP 31

32 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 2013 TPOP 32

33 Lilian Blot Special Argument-Matching Modes Positional: matched left to right  What we have seen so far Keywords: matched by argument name Autumn 2013 TPOP 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

34 Lilian Blot Special Argument-Matching Modes Defaults: specify values for arguments that are not passed varargs: catch unmatched positional or keyword arguments Autumn 2013 TPOP 34 def my_args_func(*args): #unmatched positional argument print args def my_args2_func(**args): # unmatched keyword argument print args Code


Download ppt "Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1."

Similar presentations


Ads by Google