0% found this document useful (0 votes)
22 views

Lec 4

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Lec 4

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

LEARNING OBJECTIVES

Structuring programs
Abstraction, decomposition, reuse
Functions
return keyword
Scopes

1
◼︎
◼︎
◼︎
◼︎
◼︎
MOTIVATION

What we know so far?


◦ Numbers, booleans, strings, assignments,
◦ input/output,
◦ comparisons, conditionals,
◦ and loops

2
◼︎
MOTIVATION

What about the code organisation?


◦ Each computation is a file
◦ File is a piece of code
◦ Code is a single sequence of instructions, all merged
together
Is it a good idea?

3
◼︎
◼︎
MOTIVATION

OK for small-scale problems


Messy for larger problems
Becomes progressively harder to keep track of
details as your code grows in size

4
◼︎
◼︎
◼︎
GOOD PROGRAMMING

More code not necessarily a good thing


Measure good programmers by the amount of
functionality
Introduce functions
Mechanism to achieve abstraction,
decomposition and reuse

5
◼︎
◼︎
◼︎
◼︎
You likely watch TV and use a remote to change the channel. I
necessary to build a TV and a remote, would you know how to
Probably not. But if I assembled the TV and the remote for you,
use the two to achieve a task such as changing the channel? Pr
EXAMPLE: TV REMOTE you know the inputs of each item, what each item is supposed
item outputs. Figure 20.3 and table 20.1 show inputs, behavior
cess of using a remote with a TV.

TV remote is a black box Remote Push button


Generates
a wireless Wireless signal
signal

Don't know how it works


See or hear
Image on
Know the interface: input/output
TV Wireless signal
TV changes
something
different
Figu
view

Can control any compatible TV set


Black box somehow generates a signal based on
the button pressed
ABSTRACTION: do not need to know how TV
remote works to use it!

Licensed to Gregory Chockler <[email protected]>


6
◼︎
◼︎
◼︎
◼︎
◼︎
◼︎
Modularity is the division of a big program into smaller tasks. You write code for each
task separately, independent of other tasks. In general, each code module is supposed to
stand on its own. You should be able to quickly test whether the code that you wrote for

EXAMPLE: TV REMOTE/TV SET


this module works. Dividing a larger task in this way makes the larger problem seem
easier and will reduce the time it takes you to debug.

20.2.2 Abstracting code

Task:necessary
changing TV channels decomposed into
You likely watch TV and use a remote to change the channel. If I gave you all the parts
to build a TV and a remote, would you know how to put them together?
◦ Generate a But
Probably not. wireless signal
if I assembled the TVbased on the
and the remote button
for you, pressed
would you know howon to

theuseremote
the two to achieve a task such as changing the channel? Probably. This is because
(TV remote)
you know the inputs of each item, what each item is supposed to do, and what each
◦ Accept a wireless
item outputs. Figure 20.3signal
and tablefrom the
20.1 show remote
inputs, and
behavior, and change the
output for the pro-

channel (TV set)


cess of using a remote with a TV.

Generates
Remote Push button a wireless Wireless signal
signal

See or hear
Image on
TV Wireless signal
TV changes
something Figure 20.3 Black box
different view of a remote and a TV

DECOMPOSITION: different devices work together to


solve a complex task

7
◼︎
◼︎
EXAMPLE: TV REMOTE

No need to use separate remotes to switch to


different channels
Reuse: use different inputs to produce different
outputs

8
◼︎
◼︎
APPLY THESE CONCEPTS

TO PROGRAMMING!

9
CREATE STRUCTURE with
DECOMPOSITION
Divide code into modules
◦ are self-contained
◦ used to break up code
◦ intended to be reusable
◦ keep code organised
◦ keep code coherent
This lecture: decomposition with functions
Later on: decomposition with classes

10
◼︎
◼︎
◼︎
SUPPRESS DETAILS with
ABSTRACTION
Think of a piece of code as a black box
◦ cannot see details
◦ do not need to see details
◦ do not want to see details
◦ hide tedious coding details
Achieve abstraction with function specifications
or docstrings

11
◼︎
◼︎
BEWARE OF LEAKY
ABSTRACTIONS

Avoid prematurely abstracting code


It is OK to have the occasional repetition of code
(judgement call)
It should be easy to reason about the code
◦ as much relevant information as possible should be
visible on sight
But, “All non-trivial abstractions, to some degree,
are leaky.” Joel Spolsky

12
◼︎
◼︎
◼︎
◼︎
Moodle quiz
‘Decomposition and
Abstraction’

13
FUNCTIONS

Write reusable pieces/chunks of code, called


functions
Functions are not run in a program until they are
“called” or “invoked” in a program
Function properties:
◦ has a name
◦ has parameters (0 or more)
◦ has a docstring (optional but recommended)
◦ has a body
◦ returns something

14
◼︎
◼︎
◼︎
HOW TO WRITE AND CALL/
INVOKE A FUNCTION
keyword name formal parameters or arguments
Speci cation,
def is_even( i ): docstring

"""
Indentation Input: i, a positive int

Returns True if i is even, otherwise False

"""

print('inside is_even')
Body
return i%2 == 0

is_even(3) Later in the code, call function using the name and
actual (concrete) parameters
15
fi
IN THE FUNCTION BODY

def is_even( i ):

"""

Input: i, a positive int

Returns True if i is even, otherwise False

"""

print('inside is_even') Run some commands

return i%2 == 0
Expression to
keyword evaluate and return

16
VARIABLE SCOPE
Formal parameters gets bound to the value of
actual parameters when function is called
New scope/frame/environment created when
enter a function
Scope is mapping of names to objects
formal parameter
def f(x):
function
x = x + 1
de nition global/
print('in f(x): x =', x) main
return x scope
main
x = 3 actual parameter program
z = f(x) code

17
◼︎
◼︎
◼︎
fi
VARIABLE SCOPE

18
VARIABLE SCOPE

19
VARIABLE SCOPE

20
VARIABLE SCOPE

21
VARIABLE SCOPE

22
VARIABLE SCOPE

23
VARIABLE SCOPE

24
VARIABLE SCOPE

25
VARIABLE SCOPE

26
Moodle quiz
‘functions’

27
NO RETURN STATEMENT
def is_even( i ):

"""

Input: i, a positive int

Does not return anything

"""

i%2 == 0

Python returns the value None, if no return given


Represents the absence of a value

28
◼︎
◼︎
FUNCTIONS AS PARAMETERS
(ARGUMENTS)
def func_a():
print('inside func_a')

def func_b(y):
print('inside func_b')
return y

def func_c(z):
print('inside func_c')
return z()

print(func_a())
print(5+func_b(2))
print(func_c(func_a))
29
FUNCTIONS AS ARGUMENTS
def func_a():
print('inside func_a')

def func_b(y):
print('inside func_b')
return y

def func_c(z):
print('inside func_c')
return z()

print(func_a())
print(5+func_b(2))
print(func_c(func_a))
30
FUNCTIONS AS ARGUMENTS
def func_a():
print('inside func_a')

def func_b(y):
print('inside func_b')
return y

def func_c(z):
print('inside func_c')
return z()

print(func_a())
print(5+func_b(2))
print(func_c(func_a))
31
FUNCTIONS AS ARGUMENTS
def func_a():
print('inside func_a')

def func_b(y):
print('inside func_b')
return y

def func_c(z):
print('inside func_c')
return z()

print(func_a())
print(5+func_b(2))
print(func_c(func_a))
32
FUNCTIONS AS ARGUMENTS
def func_a():
print('inside func_a')

def func_b(y):
print('inside func_b')
return y

def func_c(z):
print('inside func_c')
return z()

print(func_a())
print(5+func_b(2))
print(func_c(func_a))
33
FUNCTIONS AS ARGUMENTS
def func_a():
print('inside func_a')

def func_b(y):
print('inside func_b')
return y

def func_c(z):
print('inside func_c')
return z()

print(func_a())
print(5+func_b(2))
print(func_c(func_a))
34
VARIABLE VISIBILITY

Inside a function, can access variable defined


outside. “Shadowing” variable/name.
Inside a function, cannot modify a variable
defined outside, unless it is marked as global

def f(y): def g(y): def h(y):


x = 1 print(x) x += 1
x += 1 print(x+1) x = 5
print(x) x = 5 h(x)
x = 5 g(x) print(x)
f(x) print(x)
print(x)
35
◼︎
◼︎
VARIABLE VISIBILITY

Variables defined outside must be explicitly


designated as global before they can be modified
inside a function
May not be a good idea: breaks functional
abstraction. Avoid.
def h(y):
keyword global x
x += 1
x = 5
h(x)
print(x)

36
◼︎
◼︎
VARIABLE SCOPE

Important and tricky subject

Practice on your own

Python Tutor is your best friend to sort out


tricky cases

http://www.pythontutor.com

37
◼︎
◼︎
◼︎
Moodle quiz
‘functions as parameters’

38
NESTED SCOPES
COPE DETAILS
x): Global scope
def g(x):
f h(): g
def h(): Some
x = 'abc' code
x = 'abc'
= x + 1
x = x + 1
int('g: x =', x) x 3
print('in g(x): x =', x)
)
h()
turn x
return x z

x = 3
x)z = g(x)

6.0001 LECTURE 4 39 28
NESTED SCOPES
COPE DETAILS
SCOPE DETAILS
x):
def g(x): Global scope g scope
def g(x):
f h():def h(): g x
def h(): Some
x = 'abc' 3
x = 'abc' code
x = 'abc'
= x +x 1= x + 1
x = x + 1 Some
int('g: x =', x)
print('g: x =', x) x 3 h
print('in g(x): x =', x) code
) h()
h()
turn return
x x
return x z

x = 3
x = 3
zz ==
x) g(x)
g(x)

6.0001 LECTURE 4 6.0001 40


LECTURE 4 28 29
NESTED SCOPES
COPE DETAILS
SCOPE DETAILS
x):
def g(x): Global scope g scope
def g(x):
f h():def h(): g x
def h(): Some
x = 'abc' 43
x = 'abc' code
x = 'abc'
= x +x 1= x + 1
x = x + 1 Some
int('g: x =', x)
print('g: x =', x) x 3 h
print('in g(x): x =', x) code
) h()
h()
turn return
x x
return x z

xx == 3
3
x)
zz == g(x)
g(x)

6.0001 LECTURE 4 6.000141


LECTURE 4 28 30
NESTED SCOPES
SCOPE DETAILS
def g(x): Global scope g scope h scope
def g(x):
def h(): g x x
def h(): Some
3
4 “abc”
x = 'abc' code
x = 'abc'
x = x + 1
x = x + 1 Some
print('g: x =', x) x 3 h
print('in g(x): x =', x) code
h()
h()
return x
return x z
returns None
x = 3
x = 3
z = g(x)
z = g(x)

6.0001 LECTURE 4 31
42
NESTED SCOPES
SCOPE DETAILS
def g(x): Global scope g scope
def g(x):
def h(): g x
def h(): Some
4
x = 'abc' code
x = 'abc'
x = x + 1
x = x + 1 Some
print('g: x =', x) x 3 h
print('in g(x): x =', x) code
h()
h()
return x None
return x z

x = 3 returns 4
x = 3
z = g(x)
z = g(x)

6.0001 LECTURE 4 32
43
NESTED SCOPES
SCOPE DETAILS
def g(x): Global scope
def g(x):
def h(): g
def h(): Some
x = 'abc' code
x = 'abc'
x = x + 1
x = x + 1
print('g: x =', x) x 3
print('in g(x): x =', x)
h()
h()
return x
return x z 4

x = 3
x = 3
z = g(x)
z = g(x)

6.0001 LECTURE 4 33
44
DECOMPOSITION & ABSTRACTION

Powerful together
Code can be used many times, but only has to be
debugged once!
Example :-
len returns the length of the string

◦ s=‘abc’
◦ print(len(s))

print displays the value of the argument passed to it


45
◼︎
◼︎
◼︎
Moodle quiz
‘Nested scopes’

46

You might also like