Week 5
Course Review & Advanced Topics
Functions
Instructor: Asst. Prof. LIN Shang-Wei
Email:
[email protected]Introduction to Computational Thinking 1
Abstraction in Different Aspects
Abstraction in Data: Data Structures
Programs = Algorithms + Data Structures
(1976, Niklaus Wirth)
Abstraction in Algorithms:
Functions
Introduction to Computational Thinking 2
Function Basics
Introduction to Computational Thinking 3
Function Definition in Python
Function name must follow List of parameters being passed:
variable naming rules. in parentheses, comma-separated.
def functionName (parameter1, parameter2) :
statement1
statement2 Function suite:
Keyword Suite of the
indicating • contains code function follows
function is return to perform the colon.
defined. some action
valueToReturn
• indented
tab
Return statement: indicates the
value returned when the function
finishes.
Introduction to Computational Thinking 4
Dynamics of Function Calls
Main Program
statement
25
fahrenheit = cel2fahr(25)
statement call Function
def cel2fahr(celsius):
statement
re t u val = celsius * 1.8 +
rn
77
32
return val
Introduction to Computational Thinking 5
Q1: What is the output of the following Python program?
charList = ['a', 'e', 'i', 'o', 'u']
myStr = "This is a string!"
def funcA(content, target):
num = 0 A.0
B.1
for char in content:
if char in target:
C.2
num += 1 D.3
✔ E.4
return num
F.5
result = funcA(myStr, charList)
print(result)
Introduction to Computational Thinking 6
Q2: What is the output of the following Python program?
myStr = "Hello"
result = 0
def funcA(content):
num = 0
✔ A.0
for char in content: B.1
num += 1 C.2
D.3
return num E.4
F.5
result = funcA(myStr)
funcA(myStr)
print(result)
5
Introduction to Computational Thinking 7
Advanced Topics
Scope and Namespace
Introduction to Computational Thinking 8
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.
A function has its own scope: its function suite (body)
def myFunc(param1, param2):
statement1
statement2
…
Introduction to Computational Thinking 9
Namespace
Namespace is an association of name and objects
It looks like a dictionary, and for the most part it is (at least for modules and classes).
Names Objects
var1 23
a 1,345
myString “blah”
Introduction to Computational Thinking 10
Scope vs. Namespace
The same thing, but from different point views
Physical point of view vs. Logical point of view
Names Objects
def myFunc(param1, param2): var1 23
var1 = 23 vs.
a = 1.345 a 1,345
myString = ‘blah’
myString “blah”
Introduction to Computational Thinking 11
LEGB Rule
For Python, there are potentially multiple namespaces that could be used to determine
the object associated with a variable name.
Which one to use?
The search order of namespaces for a name:
• 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 built-ins scope.
• Else, ERROR.
Introduction to Computational Thinking 12
LEGB Rule (cont.)
search order:
Global
Local
Enclosing
Enclosing
Local
import
Global
Build-in
Build-in
ERROR
Introduction to Computational Thinking 13
Local and Global
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
myVar = 123 # global
Global Namespace Objects
def myFunc():
myVar 123
myVar = 500 # local
yourVar = -10 # local
print(myVar, yourVar)
myFunc Namespace
myVar 500 myFunc() # prints 500 -
10
yourVar -10
print(myVar) # prints 123
print(yourVar) # ERROR
Introduction to Computational Thinking 14
Enclosing
def enclosing():
myVariable = 'defined by enclosing'
def enclosed():
print('scope: ' + myVariable)
enclosed()
enclosing()
scope: defined by enclosing # output
Introduction to Computational Thinking 15
The Global Keyword
What if you really want to use or modify the global variables inside a function?
Ans: Using the global keyword in a function allows you to access global objects.
myVar = 100
Global Namespace Objects
def myFn(): myVar -1
100
global myVar
myVar = -1
myFn Namespace
myFn() myVar
print(myVar) # prints -1
Introduction to Computational Thinking 16
Functions and Scope
Introduction to Computational Thinking 17
Function’s Scope
Each function maintains a namespace for names defined locally within the function.
“Locally” means one of two things:
• a name assigned something within the function
• an argument received by invocation of the function
Introduction to Computational Thinking 18
Parameters vs. Arguments
For each argument in the function invocation, the argument’s associated object is passed
to the corresponding parameter in the function.
The argument and the parameter share an association with the same object.
Introduction to Computational Thinking 19
Parameters vs. Arguments (cont.)
If a parameter is assigned to a new value, then a new association is created.
This assignment does not affect the object associated with the argument.
Introduction to Computational Thinking 20
Parameters vs. Arguments (cont.)
When passing a mutable data structure, if the shared object is modified, both the
parameter and the argument will reflect that change.
Introduction to Computational Thinking 21
Q3: Are the results of the two program the same?
def myFun (param): def myFun (param):
param.append(4) param=[1,2,3]
return param param.append(4)
return param
myList = [1,2,3] myList = [1,2,3]
newList = myFun(myList) newList = myFun(myList)
print(myList,newList) print(myList,newList)
Program A Program B
A. Yes
✔ B. No
Introduction to Computational Thinking 22
Program A
Main Namespace Objects
def myFun (param):
param.append(4) myList
return param
newList
myList = [1,2,3] 1 2 3 4
newList = myFun(myList)
print(myList,newList) myFun Namespace
param
Program A
[1,2,3,4] [1,2,3,4] # output
Introduction to Computational Thinking 23
Program B
Main Namespace Objects
def myFun (param):
param=[1,2,3] myList
param.append(4)
return param newList
myList = [1,2,3] 1 2 3
newList = myFun(myList)
print(myList,newList) myFun Namespace
param 1 2 3 4
Program B
[1,2,3] [1,2,3,4] # output
Introduction to Computational Thinking 24
Q4: What is the output of the following Python program?
myVar = 127
A.myVar: 7
def myFun (myVar): myVar: 7
myVar = 7
print(‘myVar: ’, myVar) B.myVar: 127
myVar: 127
myFun(myVar)
print(‘myVar: ’, myVar)
✔ C.myVar: 7
myVar: 127
D.myVar: 127
myVar: 7
Introduction to Computational Thinking 25
Q5: What is the output of the following Python program?
myVar = 127
def myFun ():
a = myVar + 1
print(‘a: ’, a)
myFun()
✔ A.a: 128
B.a: 127
C.ERROR
Introduction to Computational Thinking 26
Q6: What is the output of the following Python program?
myVar = 127 myVar = 127
def myFun (): def myFun ():
How to fix it?
myVar = myVar + 1 global myVar
myVar = myVar + 1
myFun()
print(myVar) myFun()
print(myVar)
local variable ‘myVar’
A.128 referenced before assignment Objects
B.127 Main Namespace myVar 127
✔ C.ERROR
myFun Namespace myVar ??
Introduction to Computational Thinking 27