Lecture 10 user defined functions and modules

91
Introduction to computational thinking Module 10 : User defined functions and modules Asst Prof Michael Lees Office: N402c76 email: mhlees[at]ntu.edu.sg Module 10 : User defined functions and modules

Transcript of Lecture 10 user defined functions and modules

Page 1: Lecture 10  user defined functions and modules

Introduction to computational thinking

Module 10 : User defined functions and modules

Asst Prof Michael LeesOffice: N4‐02c‐76

email: mhlees[at]ntu.edu.sgModule 10 : User defined functions and 

modules

Page 2: Lecture 10  user defined functions and modules

Contents

• Function basics– Dynamics of function call

• Functions using functions• Scope and namespace• Functions and scope• Default parameters• Recursion• Stacks• Modules

Module 10 : User defined functions and modules 2 of 53

Chapter 6,Chapter 7,Chapter 16

Page 3: Lecture 10  user defined functions and modules

FUNCTION BASICSModule 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 4: Lecture 10  user defined functions and modules

What is a Function?

• From mathematics we know that functions perform some operation and return one value.

• They “encapsulate” the performance of some particular operation, so it can be used by others (for example, the sqrt() function).

Module 10 : User defined functions and modules

Page 5: Lecture 10  user defined functions and modules

Imagine you want to calculate sqrtx=10 precision =0.001low = 0

high = max(x, 1) counter = 0 guess= (low + high) /2.0 while abs (guess ** 2 -x) >

precision and counter <= 100: if(guess ** 2 < x):

low = guess else:

high = guess guess = (low + high) / 2.0 counter += 1

assert counter <= 100, '100 iterations done and no good answer' print('Num of iterations:', counter, 'Estimate:', guess)

Module 10 : User defined functions and modules 5 of 53

vs. sqrt(10)

Page 6: Lecture 10  user defined functions and modules

Why functions?

• Support divide‐and‐conquer strategy• Abstraction of an operation• Reuse: once written, use again• Sharing: if tested, others can use• Security: if well tested, then secure for reuse• Simplify code: more readable

Module 10 : User defined functions and modules

Page 7: Lecture 10  user defined functions and modules

Notation

• Consider a function which converts temperatures in Celsius to temperatures in Fahrenheit:– Formula:   F = C * 1.8 + 32.0– Functional notation: F = celsisus2Fahrenheit(C)where celsius2Fahrenheit(C) = C*1.8 + 32.0

Module 10 : User defined functions and modules

Page 8: Lecture 10  user defined functions and modules

Python invocation

• Math: F = celsius2Fahrenheit(C) • Python, the invocation is much the sameF = celsius2Fahrenheit(C)

Terminology: argument “C”

Module 10 : User defined functions and modules

Page 9: Lecture 10  user defined functions and modules

Python Function definition

• Math: g(C) = C*1.8 + 32.0• Python                                               def celsius2Fahrenheit (C):

return C*1.8 + 32.0

• Terminology: parameter “C”

Module 10 : User defined functions and modules

Tab

Page 10: Lecture 10  user defined functions and modules

Module 10 : User defined functions and modules

Page 11: Lecture 10  user defined functions and modules

Return

• The return statement indicates the value that is returned by the function.

• The statement is optional (the function can return nothing). If no return, the function is often called a procedure.

Module 10 : User defined functions and modules

Page 12: Lecture 10  user defined functions and modules

Challenge 10.1 – Convert £ to S$Write a simple function that converts currencies

Module 10 : User defined functions and modules

Page 13: Lecture 10  user defined functions and modules

Thought process

• Functions are to be re‐usable• What might change? 

– Input amount.– Exchange rate.

• Function might be used by a more complete program.

• 2 parameters : input amount, exchange rate.• Return converted amount.

Module 10 : User defined functions and modules

Page 14: Lecture 10  user defined functions and modules

Comments on functions

• A triple quoted string just after the def is called a docstring

• docstring is documentation of the function’s purpose, to be used by other tools to tell the user what the function is used for.

• Very important! – Habits form early!

Module 10 : User defined functions and modules

Page 15: Lecture 10  user defined functions and modules

Operation

Module 10 : User defined functions and modules

def celsius2Fahrenheit (Temp):return temp*1.8 + 32.0

F = celsius2Fahrenheit(C) 1. Call copies argument C to parameter Temp 

2. Control transfers to function “celsius2Farenheit”

c=10

temp=10

Page 16: Lecture 10  user defined functions and modules

Operation cont

Module 10 : User defined functions and modules

3. Expression in celsius2Farenheit is evaluated

4. Value of expression is returned to the invoker

F = celsius2Fahrenheit(C) 

def celsius2Fahrenheit (Temp):return Temp*1.8 + 32.0

temp=10

return 10*1.8+32.0return 50

F=50

Page 17: Lecture 10  user defined functions and modules

Module 10 : User defined functions and modules

Page 18: Lecture 10  user defined functions and modules

Challenge 10.2 – Create encryption functionModify the code from module 8, to use a function for encrypting a string

Module 10 : User defined functions and modules

Page 19: Lecture 10  user defined functions and modules

Thought process

• Code Refactoring : disciplined way to restructure code. (improve readability, reduce complexity, improve maintainability)

• What should be the parameters?• What should the function return?• Can use our ASCIIshift as input.

Module 10 : User defined functions and modules

Page 20: Lecture 10  user defined functions and modules

How to write a function

• Does one thing. If it does too many things, it should be broken down into multiple functions (refactored).

• Readable.  How often should we say this? If you write it, it should be readable.

• Reusable. If it does one thing well, then when a similar situation (in another program) occurs, use it there as well.

Module 10 : User defined functions and modules

Page 21: Lecture 10  user defined functions and modules

More on how to write

• Complete. A function should check for all the cases where it might be invoked. Check for potential errors.

• Not too long. Kind of synonymous with “does one thing”. Use it as a measure of doing too much.

Module 10 : User defined functions and modules

Page 22: Lecture 10  user defined functions and modules

Procedures

• Functions that have no return statements are often called procedures.

• Procedures are used to perform some duty (print output, store a file, etc.)

• Remember, return is not required.

Module 10 : User defined functions and modules

Page 23: Lecture 10  user defined functions and modules

Multiple returns

• A function can have multiple return statements.

• Remember, the first return statement executed ends the function.

• Multiple returns can be confusing to the reader and should be used carefully.

Module 10 : User defined functions and modules

Page 24: Lecture 10  user defined functions and modules

FUNCTIONS USING FUNCTIONSModule 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 25: Lecture 10  user defined functions and modules

Functions calling functions

• Functions are made to solve a problem and can be called from other functions.

• Functions calling functions does not do anything we haven’t already seen, but it can make following the flow of a program more difficult.

Module 10 : User defined functions and modules

Page 26: Lecture 10  user defined functions and modules

def isFloat(aStr):

"""True if aStr is a float: digits and at most one decimal point"""

print("*** In the isFloat function.”)

# remove the decimal point

stripped = aStr.replace('.','',1)

# only digits should remain

return stripped.isdigit()

Module 10 : User defined functions and modules

Page 27: Lecture 10  user defined functions and modules

def readFloat(prompt):

"""Keep reading until a valid float is entered"""

print(" *** In readFloat function.”)

num_str = raw_input(prompt)

# keep asking until valid float

while not isFloat(num_str):

print(’Invalid float, try again’)

num_str = raw_input(prompt)

return float(num_str)

Module 10 : User defined functions and modules

Page 28: Lecture 10  user defined functions and modules

Chaining functions

• isFloat checks to see if a string can be converted to a float number.

• readFloat uses isFloat as part of the process of prompting until a float is returned by the user.

• There is no limit to the “depth” of multiple function calls.

Module 10 : User defined functions and modules

Page 29: Lecture 10  user defined functions and modules

SCOPE AND NAMESPACEModule 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 30: Lecture 10  user defined functions and modules

Defining scope

“The set of program statements over which a variable exists, i.e. can be referred to.”

• It is about understanding, for any variable, what its associated value is.

Module 10 : User defined functions and modules

Page 31: Lecture 10  user defined functions and modules

Namespace

• Namespace is an association of name and objects• William of Orange vs. William of Ockham

• GoogleMaps library vs YahooMaps library –getAddress(), getDirections()

Module 10 : User defined functions and modules

Page 32: Lecture 10  user defined functions and modules

Namespace continued

• Namespaces in python are important• It looks like a dictionary, and for the most part it is (at least for modules and classes).

• For Python, there are potentially multiple namespaces that could be used to determine the object associated with a variable. 

Module 10 : User defined functions and modules

Page 33: Lecture 10  user defined functions and modules

Namespace

Module 10 : User defined functions and modules 33 of 53

var1

a

myString

23

1.345

“blah”

names python objects

Page 34: Lecture 10  user defined functions and modules

Scope and namespace

• What namespace you might be using is part of identifying the scope of the variables and function you are using.

• Remember, by “scope”, we mean the context, the part of the code, where we can make a reference to a variable or function.

Module 10 : User defined functions and modules

Page 35: Lecture 10  user defined functions and modules

Multiple Scopes

• Often, there can be multiple scopes that are candidates for determining a reference.

• Knowing which one is the right one (or more importantly, knowing the order of scope) is important.

Module 10 : User defined functions and modules

Page 36: Lecture 10  user defined functions and modules

Two kinds of namespace

• Unqualified namespaces: this is what we have pretty much seen so far ‐ functions, assignments, etc.

• Qualified namespaces: these are for modules and classes (we don’t cover these, but you should be aware they are different).

Module 10 : User defined functions and modules

Page 37: Lecture 10  user defined functions and modules

Unqualified

• This is the standard assignment and def we have seen so far.

• Determining the scope of a reference identifies what its true ‘value’ is.

Module 10 : User defined functions and modules

Page 38: Lecture 10  user defined functions and modules

Unqualified follow LEGB rule

• Local : inside the function in which it was defined.• Enclosing : If not there, enclosing/encompassing. Is it defined in an enclosing function?

• Global : If not there, is it defined in the global namespace?

• Built‐in : Finally, check the built‐in, defined as part of the special builtin scope.

• Else, ERROR.

Module 10 : User defined functions and modules

Page 39: Lecture 10  user defined functions and modules

Local

• If a reference is assigned in a function, then that reference is only available within that function.

• If a reference with the same name is provided outside the function, the reference is reassigned.

Module 10 : User defined functions and modules

Page 40: Lecture 10  user defined functions and modules

Local and GlobalmyVar = 123 # global

def myFn(myVar=456): # parameter is local

yourVar = -10 # assignment local

print(myVar, yourVar)

myFn() # prints 456 -10

myFn(500) # prints 500 -10

myVar # prints 123

yourVar # ERROR

Module 10 : User defined functions and modules

Page 41: Lecture 10  user defined functions and modules

Enclosing'''Simple test of Python scoping rules'''

def enclosing():myvariable = ’defined by enclosing'

def enclosed():print(’scope: ' + myvariable)

myfunction()

enclosing()

Module 10 : User defined functions and modules

Page 42: Lecture 10  user defined functions and modules

Built‐in

• This is just the standard library of Python. • To see what is there, look atimport __builtin__dir(__builtin__)

Module 10 : User defined functions and modules

Page 43: Lecture 10  user defined functions and modules

Global Statement

• You can “cheat” by using the global keyword in a function:myVar = 100

def myFn():

global myVar

myVar = -1

myFn()print(myVar) # prints ‐1

Module 10 : User defined functions and modules

Page 44: Lecture 10  user defined functions and modules

FUNCTIONS AND SCOPEModule 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 45: Lecture 10  user defined functions and modules

Function’s namespace

• Each function maintains a namespace for names defined locally within the function. 

• Locally means one of two things:– a name assigned within the function– an argument received by invocation of the function

Module 10 : User defined functions and modules

Page 46: Lecture 10  user defined functions and modules

Passing argument ‐> parameter

• For each argument in the function invocation, the argument’s associated object is passed to the corresponding parameter in the function.

Module 10 : User defined functions and modules

Page 47: Lecture 10  user defined functions and modules

Module 10 : User defined functions and modules

Page 48: Lecture 10  user defined functions and modules

What is pass?

• The diagram should make it clear that the parameter name is local to the function namespace.

• Passing means that the argument and the parameter, named in two different namespaces, share an association with the same object.

• So “passing” means “sharing” in Python.

Module 10 : User defined functions and modules

Page 49: Lecture 10  user defined functions and modules

Assignment changes association

• If a parameter is assigned to a new value, then just like any other assignment, a new association is created.

• This assignment does not affect the object associated with the argument, as a new association was made with the parameter.

Module 10 : User defined functions and modules

Page 50: Lecture 10  user defined functions and modules

Module 10 : User defined functions and modules

Page 51: Lecture 10  user defined functions and modules

Passing/sharing mutables

• When passing a mutable data structure, it is possible that if the shared object is directly modified, both the parameter and the argument will reflect that change.

• Note that the operation must be a mutable change, a change of the object. An assignment is not such a change.

Module 10 : User defined functions and modules

Page 52: Lecture 10  user defined functions and modules

Module 10 : User defined functions and modules

[1, 2, 3]

Page 53: Lecture 10  user defined functions and modules

MORE ON FUNCTIONSModule 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 54: Lecture 10  user defined functions and modules

Single returns

• Functions return one thing, but it can be a ‘chunky’ thing. For example, it can return a tuple.

• Thus, multiple things can be returned by being packed into a tuple or other data structure.def foo():

a = 2

b = 3

return a,b

Module 10 : User defined functions and modules

Page 55: Lecture 10  user defined functions and modules

Assignment in a function

• If you assign a value in a function, that name becomes part of the local namespace of the function.

• It can have some odd effects.

Module 10 : User defined functions and modules

Page 56: Lecture 10  user defined functions and modules

Example a vs b

def myFun (param):

param.append(4)

return param

myList = [1,2,3]

newList = myFun(myList)

print(myList,newList)

Module 10 : User defined functions and modules

def myFun (param):

param=[1,2,3]

param.append(4)

return param

myList = [1,2,3]

newList = myFun(myList)

print(myList,newList)

a b

Page 57: Lecture 10  user defined functions and modules

EXAMPLE AModule 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 58: Lecture 10  user defined functions and modules

1 2 3

Name valuemyList

Main Namespace

Name valueparam

foo Namespace

Param=myList

Page 59: Lecture 10  user defined functions and modules

1 2 3

Name valuemyList

Main Namespace

Name valueparam

foo Namespace

Param=myList

4

Page 60: Lecture 10  user defined functions and modules

EXAMPLE BModule 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 61: Lecture 10  user defined functions and modules

1 2 3

Name valuemyList

Main Namespace

Name valueparam

foo Namespace

Param=myList

Page 62: Lecture 10  user defined functions and modules

1 2 3

Name valuemyList

Main Namespace

Name valueparam

foo Namespace

Param=myList

1 2 3

Page 63: Lecture 10  user defined functions and modules

1 2 3

Name valuemyList

Main Namespace

Name valueparam

foo Namespace

Param=myList

1 2 3 4

Page 64: Lecture 10  user defined functions and modules

Assignment to local

• Assignment creates a local variable.• Changes to a local variable affect only the local context, even if it is a parameter and mutable.

• If a variable is assigned locally, you cannot reference it before this assignment, even if it exists in main as well.

Module 10 : User defined functions and modules

Page 65: Lecture 10  user defined functions and modules

DEFAULTS PARAMETERS & ARGUMENTS

Module 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 66: Lecture 10  user defined functions and modules

Named parameters

def box(height=10,width=10,depth=10,color= "blue“ ):... do something ...

The parameter assignment means two things:• if the caller does not provide a value, the default is the parameter assigned value

• you can get around the order of parameters by using the name 

Module 10 : User defined functions and modules

Page 67: Lecture 10  user defined functions and modules

Defaults

def box (height=10,width=10,length=10):

print(height,width,length)

box() # prints 10 10 10

Module 10 : User defined functions and modules

Page 68: Lecture 10  user defined functions and modules

Named Parameter

def box (height=10,width=10,length=10):

print(height,width,length)

box(length=25,height=25)

# prints 25 10 25

box(15,15,15) # prints 15 15 15

Module 10 : User defined functions and modules

Page 69: Lecture 10  user defined functions and modules

Name use works in general

def foo(a,b):print(a,b)

foo(1,2) # prints 1 2

foo(b=1,a=2) # prints 2 1

Module 10 : User defined functions and modules

Page 70: Lecture 10  user defined functions and modules

Arbitrary arguments

• It is also possible to pass an arbitrary number of arguments to a function.

• The function simply collects all the arguments (no matter how few or many) into a tuple to be processed by the function.

• Tuple parameter preceded by an * (which is not part of the parameter name, it is part of the language).

• Positional arguments only.

Module 10 : User defined functions and modules

Page 71: Lecture 10  user defined functions and modules

Exampledef aFunc(fixedParam,*tupleParam):

print(‘fixed =‘,fixedParam)print(‘tuple=‘,tupleParam)

aFunc(1,2,3,4)=> fixed=1

tuple=(2,3,4)aFunc(1)=> fixed=1

tuple=()aFunc(fixedParam=4) fixed=1

tuple=()aFunc(tupleParam=(1,2,3),fixedParam=1)=> ERROR

Module 10 : User defined functions and modules

Page 72: Lecture 10  user defined functions and modules

RECURSIONModule 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 73: Lecture 10  user defined functions and modules

Recursion

• It is possible for a function to call itself.• Can be a useful tool in computing, important aspect of computer science.

• e.g., def f(n):

if n == 0:

return 1

else:return n * f(n – 1) #(what is f?)

Module 10 : User defined functions and modules

Page 74: Lecture 10  user defined functions and modules

Ackermann function

• The Ackermann function is the simplest example of a well‐defined total function which is computable but not primitive recursive, providing a counterexample to the belief in the early 1900s that every computable function was also primitive recursive (Dötzel 1991).

• Primitive recursive: A function that can be implemented using only do‐loops is called primitive recursive.

Module 10 : User defined functions and modules

Page 75: Lecture 10  user defined functions and modules

Ackermann function

Module 10 : User defined functions and modules

• Definition:

Page 76: Lecture 10  user defined functions and modules

Challenge 10.3 – Write AckermannWrite an implementation of the Ackermann function

Module 10 : User defined functions and modules

Page 77: Lecture 10  user defined functions and modules

Translate

Module 10 : User defined functions and modules

calls =0def naive_ackermann(m, n):

global callscalls += 1if m == 0:

return n + 1elif n == 0:

return naive_ackermann(m - 1, 1)else:

return naive_ackermann(m - 1, naive_ackermann(m, n - 1))

print(“Value: {}“.format(naive_ackermann(3,3)))print(“Calls: {}”.format(calls))

Page 78: Lecture 10  user defined functions and modules

STACKModule 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 79: Lecture 10  user defined functions and modules

The stack

• A Stack is a data structure, like a List or a Dictionary, but with a few different characteristics.

• A Stack is a sequence.• A Stack only allows access to one end of its data, the top of the stack.

Module 10 : User defined functions and modules 79 of 53

Page 80: Lecture 10  user defined functions and modules

Operations

Module 10 : User defined functions and modules 80 of 53

• pop: remove top of stack. Stack is one element smaller.• push (val): add val to the stack. Val is now the top. Stack 

is one element larger.• top: Reveals the top of the stack. No modification to 

stack.

Page 81: Lecture 10  user defined functions and modules

Stack of function calls

Python maintains a stack of function calls.• If a function calls another function, the new function is pushed onto the calling stack and the previous function waits.

• The top is always the active function.• When a pop occurs (function ends), the function below becomes active.

Module 10 : User defined functions and modules 81 of 53

Page 82: Lecture 10  user defined functions and modules

Stack of factorial (4)

Module 10 : User defined functions and modules 82 of 53

Page 83: Lecture 10  user defined functions and modules

USER DEFINED MODULESModule 10 : User defined functions and modules

Module 10 : User defined functions and modules

Page 84: Lecture 10  user defined functions and modules

Modules

• Modules are files containing collections of code (functions, classes)– import <moduleName>– e.g.,

Module 10 : User defined functions and modules

Page 85: Lecture 10  user defined functions and modules

User defined modules

• If you have some code which you may find useful across many programs, you can create a module.

• Just place the code in a file and call it– moduleName.py

• Then you can – import moduleName– python must be able to find moduleName.py

Module 10 : User defined functions and modules

Page 86: Lecture 10  user defined functions and modules

Executable code in modules

• A module can include variable definitions and executable code that will be executed on first import.

• Modules can also be run from the command line as scripts:– python moduleName.py

Module 10 : User defined functions and modules

Page 87: Lecture 10  user defined functions and modules

Example

File: area.py

pi = 3.1419

def areaCircle(radius):

return pi*radius*radius

def areaSquare(edge):

return edge*edge

print(‘==Module loaded==’)

Module 10 : User defined functions and modules

File: circle.py

import area

print(area.pi)print(area.areaCircle(3))

Page 88: Lecture 10  user defined functions and modules

Modules as scripts

• The code in the module will be executed, just as if you imported it, but with the __name__set to "__main__". 

• That means that by adding this code at the end of your module:

if __name__ == "__main__":

print(‘run as script’)• The code in the if statement will only execute if the file is run as a script.

Module 10 : User defined functions and modules

Page 89: Lecture 10  user defined functions and modules

Module path

• When a module named moduleName is imported, the interpreter searches for a file named moduleName.py in the directory containing the input script and then in the list of directories specified by the environment variable PYTHONPATH. 

• Operating system dependent.

Module 10 : User defined functions and modules

Page 90: Lecture 10  user defined functions and modules

Take home lessons

• Understand functions and their call structure– Why do we need functions?

• How to define your own function– what is a good function?

• Namespaces & scope – What are they for, what’s their relationship?

• Parameters (named) & arguments• Recursion & stack

– recursion is another tool in the arsenal. Careful of stack becoming too big!

Module 10 : User defined functions and modules 90 of 53

Page 91: Lecture 10  user defined functions and modules

Further reading/watching

• http://docs.python.org/library/functions.html

• http://www.youtube.com/watch?v=SXR9CDof7qw

• http://www.youtube.com/watch?v=cKzhdxCPU3Y

• http://cpsc110.umwblogs.org/2011/04/14/april‐14‐2011‐functions/

Module 10 : User defined functions and modules 91 of 53