0% found this document useful (0 votes)
17 views34 pages

Lec 4

Uploaded by

wanguenhle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views34 pages

Lec 4

Uploaded by

wanguenhle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

DECOMPOSITION,

ABSTRACTION,
FUNCTIONS
(download slides and .py files and follow
along!)
LECTURE 4

6.0001 LECTURE 4 1
LAST
TIME
while loops vs for loops
 should know how to write both kinds
 should know when to use them
 guess-and-check and approximation methods
 bisection method to speed up programs

6.0001 LECTURE 4 2
TOD
AY
structuring programs and hiding details
 functions
 specifications
 keywords: return vs print
 scope

6.0001 LECTURE 4 3
HOW DO WE WRITE
CODE?
so far…
• covered language mechanisms
• know how to write different files for each computation
• each file is some piece of code
• each code is a sequence of instructions
 problems with this approach
• easy for small-scale problems
• messy for larger problems
• hard to keep track of details
• how do you know the right info is supplied to the
right part of code
6.0001 LECTURE 4 4
GOOD
PROGRAMMING
more code not necessarily a good thing
measure good programmers by the amount of
functionality
 introduce functions
 mechanism to achieve decomposition and
abstraction

6.0001 LECTURE 4 5
EXAMPLE –
PROJECTOR
a projector is a black box
 don’t know how it works
 know the interface: input/output
connect any electronic to it that can communicate
with that input
black box somehow converts image from input source
to a wall, magnifying it
ABSTRACTION IDEA: do not need to know how
projector works to use it

6.0001 LECTURE 4 6
EXAMPLE –
PROJECTOR
projecting large image for Olympics decomposed into
separate tasks for separate projectors
each projector takes input and produces separate
output
 all projectors work together to produce larger
image
DECOMPOSITION IDEA: different devices work
together to achieve an end goal

6.0001 LECTURE 4 7
APPLY THESE
CONCEPTS
TO
PROGRAMMING!

6.0001 LECTURE 4 8
CREATE STRUCTURE
DECOMPOSITION
with
 in projector example, separate devices
 in programming, divide code into modules
• are self-contained
• used to break up code
• intended to be reusable
• keep code organized
• keep code coherent
 this lecture, achieve decomposition with functions
 in a few weeks, achieve decomposition with classes

6.0001 LECTURE 4 9
SUPRESS DETAILS
ABSTRACTION
with
in projector example, instructions for how to use it are
sufficient, no need to know how to build one
 in programming, 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

6.0001 LECTURE 4 10
FUNCTIO
NS
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 characteristics:
• has a name
• has parameters (0 or more)
• has a docstring (optional but recommended)
• has a body
• returns something

6.0001 LECTURE 4 11
HOW TO WRITE and
CALL/INVOKE A FUNCTION
def is_even( i ):
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
print("inside is_even")
return i%2 == 0

is_even(3)

6.0001 LECTURE 4 12
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")
return i%2 == 0

6.0001 LECTURE 4 13
VARIABLE
SCOPE
 formal parameter gets bound to the value of
actual parameter when function is called
 new scope/frame/environment created when enter a function
 scope is mapping of names to objects
def f( x ):
x = x + 1
print('in f(x): x =', x)
return x

x = 3
z = f( x )

6.0001 LECTURE 4 14
VARIABLE
SCOPE

def f( x ): Global scope f scope


x = x + 1
Some
print('in f(x): x =', x) f code
x 3
return x
x 3
x = 3
z = f( x )

6.0001 LECTURE 4 15
VARIABLE
SCOPE

def f( x ): Global scope f scope


x = x + 1
Some
print('in f(x): x =', x) f code
x 4
return x
x 3
x = 3
z = f( x )

6.0001 LECTURE 4 16
VARIABLE
SCOPE

def f( x ): Global scope f scope


x = x + 1
Some x
print('in f(x): x =', x) f 4
return x code
x 3 returns 4
x = 3
z = f( x ) z
6.0001 LECTURE 4 17
VARIABLE
SCOPE

def f( x ): Global scope


x = x + 1
Some
print('in f(x): x =', x) f code
return x
x 3
x = 3
z = f( x ) 4

6.0001 LECTURE 4 18
ONE WARNING IF 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
6.0001 LECTURE 4 19
return vs.
 return only has meaning  print can be used outside
print
inside a function functions
only one return executed can execute many print
inside a function statements inside a function
code inside function but
code inside function can be
after return statement not
executed executed after a print
statement
has a value associated
with it, given to function has a value associated with
caller it, outputted to the console

6.0001 LECTURE 4 20
FUNCTIONS AS
ARGUMENTS
arguments can take on any type, even functions
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)
6.0001 LECTURE 4 21
FUNCTIONS AS
ARGUMENTS
def func_a():
Global scope func_a scope

func_a Some
print 'inside func_a' code
def func_b(y): Some
func_b
print 'inside func_b'
code
return y Some
def func_c(z): func_c
code
print 'inside func_c'
None returns None
return z()
print func_a()
print 5 + func_b(2)
func_c(func_a)
print 6.0001 LECTURE 4 22
FUNCTIONS AS
ARGUMENTS
def func_a():
Global scope func_b scope

func_a Some y 2
print 'inside func_a' code
def func_b(y): Some
func_b
print 'inside
code
func_b' return y Some
def func_c(z): func_c
code
print 'inside None
func_c' return z()
print func_a() 7 returns 2
print 5 + func_b(2)
print func_c(func_a)
6.0001 LECTURE 4 23
FUNCTIONS AS ARGUMENTS
Global scope func_c scope
def func_a(): func_a Some
z func_a
print 'inside func_a' code
def func_b(y): Some
func_b code
print 'inside func_b'
return y Some func_a scope
func_c code
def func_c(z):
print 'inside func_c' None
return z()
7 returns None
print func_a()
print 5 + func_b(2)
None returns None
print func_c(func_a)
6.0001 LECTURE 4
SCOPE
EXAMPLE
inside a function, can access a variable defined outside
inside a function, cannot modify a variable defined
outside -- can using global variables, but frowned upon
def f(y): def g(y): def h(y):
x = 1 print(x) x +=
x += 1 print(x + 1)
1 x = 5
print x = 5 h(x)
x = 5(x) g(x) print(x)
f(x) print(x)
print(x)

6.0001 LECTURE 4 25
SCOPE
EXAMPLE
inside a function, can access a variable defined outside
inside a function, cannot modify a variable defined
outside -- can using global variables, but frowned upon
def f(y): def g(y): def h(y):
x = 1 print(x) x += 1
x +=
1 x = 5
print x = 5 h(x)
x = 5
(x) g(x) print(x)
f(x) print(x)
print(x)

6.0001 LECTURE 4 26
HARDER SCOPE
EXAMPLE IMPORTANT
and
TRICKY!

Python Tutor is your best friend to


help sort this out!
http://www.pythontutor.com/
6.0001 LECTURE 4 27
SCOPE
DET
def g(x): AILS
def h():
Global scope

g Some
x = 'abc'
x = x + 1 code

print('g: x =', x) x 3
h()
return x
z

x = 3
= g(x)
z

6.0001 LECTURE 4 28
SCOPE
DET
def g(x): AILS
def h():
Global scope g scope

g Some x
x = 'abc' 3

x = x + 1 code
x h Some
print('g: x =', x) 3
h() code
return x
z

x = 3
= g(x)
z

6.0001 LECTURE 4 29
SCOPE
DET
def g(x): AILS
def h():
Global scope g scope

g Some x
x = 'abc' 43

x = x + 1 code
x h Some
print('g: x =', x) 3
h() code
return x
z

x = 3
= g(x)
z

6.0001 LECTURE 4 30
SCOPE
DET
def g(x): AILS
def h():
Global scope g scope h scope

g Some x x
x = 'abc' 3
4 “abc”

x = x + 1 code
x h Some
print('g: x =', x) 3
h() code
return x
z
returns None
x = 3
z = g(x)

6.0001 LECTURE 4 31
SCOPE
DET
def g(x): AILS
def h():
Global scope g scope

g Some x
x = 'abc' 4

x = x + 1 code

x h Some
print('g: x =', x) 3
h() code
return x
None
z

x = 3
returns 4
= g(x)
z

6.0001 LECTURE 4 32
SCOPE
DET
def g(x): AILS
def h():
Global scope

g Some
x = 'abc'
x = x + 1 code

print('g: x =', x) x 3
h()
return x
z 4

x = 3
= g(x)
z

6.0001 LECTURE 4 33
DECOMPOSITION &
ABSTRACTION
 powerful together
code can be used many times but only has to be
debugged once!

6.0001 LECTURE 4 34

You might also like