Functions: Unit 4
Functions: Unit 4
Unit 4
§ 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
2
2
§ structuring programs and hiding details
§ functions
§ specifications
§ keywords: return vs print
§ scope
3
3
§ 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
4
4
§more code not necessarily a good thing
§measure good programmers by the amount of
functionality
§ introduce functions
§ mechanism to achieve decomposition and abstraction
5
5
§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
6
§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
7
7
8
8
§ 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
9
9
§ 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
10
10
§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
11
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)
12
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
13
§ formal parameter gets bound to the value of
§ def f( x ):
§x = x + 1
print('in f(x): x =', x)
return x
x = 3
z = f( x )
14
def f( x ):
Global scope f scope
x = x + 1
Some 3
print('in f(x): x =', x) f code x
return x
3
x
x = 3
z = f( x )
z
15
def f( x ):
Global scope f scope
x = x + 1
Some 4
print('in f(x): x =', x) f code x
return x
3
x = 3 x
z = f( x )
z
16
def f( x ): Global scope
f scope
x = x + 1
f Some 4
print('in f(x): x =', x) code x
return x
x 3
x = 3 returns 4
z = f( x ) z
17
def f( x ): Global scope
x = x + 1
Some
print('in f(x): x =', x) f code
return x
3
x
x = 3
z = f( x ) 4
z
18
def is_even( i ):
"""
Input: i, a positive int
19
VS.
§return only has meaning §print can be used outside
inside a function § functions
§only one return executed §can execute many print
inside a function statements inside a function
§code inside function wont §code inside function can be
be executed if it is executed after a print
located after the return statement
statement
§has a value associated §has a value associated with
with it, given to function it, outputted to the console
caller
20
20
§ 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))
21
Global scope func_a
func_ascope
scope
def func_a(): Some
func_a
print ('inside func_a') code
def func_b(y): Some
func_b
print ('inside func_b’) code
return y Some
func_c
code
def func_c(z):
print ('inside func_c') None
returns None
return z()
print (func_a())
print (5 + func_b(2))
print (func_c(func_a))
22
Global scope func_b
func_bscope
scope
def func_a(): Some 2
func_a y
print ('inside func_a') code
def func_b(y): Some
func_b code
print ('inside func_b’)
return y Some
def func_c(z): func_c code
25
25
§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
print(x) x = 5
x = 5 h(x)
x = 5 g(x) print(x)
f(x) print(x)
print(x)
26
Python Tutor isyour best friend to help
sort this out!
http://www.pythontutor.com/visualize.
html#mode=edit
27
Global scope
def g(x):
def h(): g Some
x = 'abc' code
x = x + 1
3
x
print('g: x =', x)
h()
return x
z
x = 3
z = g(x)
28
Global scope g scope
def g(x):
def h(): g Some x 3
code
x = 'abc'
x = x + 1 3 Some
x h
print('g: x =', x) code
h()
return x
z
x = 3
z = g(x)
29
Global scope g scope
def g(x):
def h(): g Some x 4
code
x = 'abc'
x = x + 1 3 Some
x h
print('g: x =', x) code
h()
return x
z
x = 3
z = g(x)
30
30
Global scope g scope h scope
def g(x):
def h(): g Some x 3
4 x “abc”
code
x = 'abc'
x = x + 1 3 Some
x h
print('g: x =', x) code
h()
return x
z
returns None
x = 3
z = g(x)
31
def g(x): Global scope g scope
x = x + 1
3 Some
print('g: x =', x) x h code
h()
None
return x
z
x = 3 returns 4
z = g(x)
32
def g(x): Global scope
h()
return x 4
z
x = 3
z = g(x)
33
§powerful together
§code can be used many times but only has to be
debugged once!
34