Cours Mit
Cours Mit
1
FUNCTION FROM LAST LECTURE
def is_even( i ):
"""
Input: i, a positive int
Returns True if i is even and False otherwise
"""
return i%2 == 0
6.100L Lecture 8
WHAT IF THERE IS
NO return KEYWORD
def is_even( i ):
"""
Input: i, a positive int
Does not return anything
"""
i%2 == 0
6.100L Lecture 8
def is_even( i ):
"""
Input: i, a positive int
Does not return anything
"""
i%2 == 0
return None
6.100L Lecture 8
YOU TRY IT!
What is printed if you run this code as a file?
def add(x,y):
return x+y
def mult(x,y):
print(x*y)
add(1,2)
print(add(2,3))
mult(3,4)
print(mult(4,5))
6.100L Lecture 8
return vs. print
6.100L Lecture 8
YOU TRY IT!
Fix the code that tries to write this function
def is_triangular(n):
""" n is an int > 0
Returns True if n is triangular, i.e. equals a continued
summation of natural numbers (1+2+3+...+k), False otherwise """
total = 0
for i in range(n):
total += i
if total == n:
print(True)
print(False)
6.100L Lecture 8
FUNCTIONS SUPPORT
MODULARITY
Here is our bisection square root method as a function
def bisection_root(x):
epsilon = 0.01
low = 0
Initialize variables
high = x
ans = (high + low)/2.0
guess not close enough
while abs(ans**2 - x) >= epsilon:
if ans**2 < x:
iterate update low or high,
low = ans depends on guess too
else: small or too large
high = ans
ans = (high + low)/2.0 new value for guess
# print(ans, 'is close to the root of', x)
return ans return result
6.100L Lecture 8
FUNCTIONS SUPPORT
MODULARITY
Call it with different values
print(bisection_root(4))
print(bisection_root(123))
6.100L Lecture 8
YOU TRY IT!
Write a function that satisfies the following specs
def count_nums_with_sqrt_close_to (n, epsilon):
""" n is an int > 2
epsilon is a positive number < 1
Returns how many integers have a square root within epsilon of n """
10
6.100L Lecture 8
ZOOMING OUT
11
6.100L Lecture 8
ZOOMING OUT
12
6.100L Lecture 8
ZOOMING OUT
15
13
6.100L Lecture 8
FUNCTION SCOPE
14
6.100L Lecture 8
UNDERSTANDING FUNCTION
CALLS
15
6.100L Lecture 8
ENVIRONMENTS
Global environment
Where user interacts with Python interpreter
Where the program starts out
Invoking a function creates a new environment (frame/scope)
16
6.100L Lecture 8
VARIABLE SCOPE
xy = 3
z = f( y
x )
17
6.100L Lecture 8
VARIABLE SCOPE
after evaluating def
x = 3
z = f( x )
18
6.100L Lecture 8
VARIABLE SCOPE
after exec 1st assignment
6.100L Lecture 8
VARIABLE SCOPE
after f invoked
6.100L Lecture 8
VARIABLE SCOPE
after f invoked
6.100L Lecture 8
VARIABLE SCOPE
eval body of f in f’s scope
6.100L Lecture 8
VARIABLE SCOPE
during return
6.100L Lecture 8
VARIABLE SCOPE
after exec 2nd assignment
6.100L Lecture 8
BIG IDEA
You need to know what
expression you are executing
to know the scope you are in.
25
6.100L Lecture 8
ANOTHER SCOPE EXAMPLE
26
6.100L Lecture 8
FUNCTIONS as
ARGUMENTS
27
6.100L Lecture 8
HIGHER ORDER PROCEDURES
28
6.100L Lecture 8
OBJECTS IN A PROGRAM
function
my_func object with
some code
is_even
pi = 22/7
a False
my_func = is_even
b True
a = is_even(3)
b = my_func(4)
29
6.100L Lecture 8
BIG IDEA
Everything in Python is
an object.
30
6.100L Lecture 8
FUNCTION AS A PARAMETER
def add(a,b):
return a+b
def div(a,b):
if b != 0:
return a/b
print("Denominator was 0.")
print(calc(add, 2, 3))
31
6.100L Lecture 8
STEP THROUGH THE CODE
res
32
6.100L Lecture 8
CREATE calc SCOPE
res
33
6.100L Lecture 8
MATCH FORMAL PARAMS in calc
res
34
6.100L Lecture 8
FIRST (and only) LINE IN calc
res
35
6.100L Lecture 8
CREATE SCOPE OF add
res
36
6.100L Lecture 8
MATCH FORMAL PARAMS IN add
res
37
6.100L Lecture 8
EXECUTE LINE OF add
res
returns 5
38
6.100L Lecture 8
REPLACE FUNC CALL WITH RETURN
res
39
6.100L Lecture 8
EXECUTE LINE OF calc
res
returns 5
40
6.100L Lecture 8
REPLACE FUNC CALL WITH RETURN
res 5
41
6.100L Lecture 8
YOU TRY IT!
Do a similar trace with the function call
def calc(op, x, y):
return op(x,y)
def div(a,b):
if b != 0:
return a/b
print("Denom was 0.")
res = calc(div,2,0)
42
6.100L Lecture 8
ANOTHER EXAMPLE:
FUNCTIONS AS PARAMS
def func_a():
print('inside func_a')
def func_b(y):
print('inside func_b')
return y
def func_c(f, z):
print('inside func_c')
return f(z)
print(func_a())
print(5 + func_b(2))
print(func_c(func_b, 3))
43
6.100L Lecture 8
FUNCTIONS AS PARAMETERS
print('inside func_c')
return f(z)
print(func_a())
print(5 + func_b(2))
print(func_c(func_b, 3))
44
6.100L Lecture 8
FUNCTIONS AS PARAMETERS
6.100L Lecture 8
FUNCTIONS AS PARAMETERS
Global scope
def func_a(): Some
func_a
print('inside func_a') code
def func_b(y): Some
func_b code
print('inside func_b')
return y Some
def func_c(f, z): func_c code
print('inside func_c')
return f(z)
print(func_a())
print(5 + func_b(2))
print(func_c(func_b, 3))
46
6.100L Lecture 8
FUNCTIONS AS PARAMETERS
6.100L Lecture 8
FUNCTIONS AS PARAMETERS
6.100L Lecture 8
FUNCTIONS AS PARAMETERS
6.100L Lecture 8
FUNCTIONS AS PARAMETERS
Global scope
def func_a(): Some
func_a
print('inside func_a') code
def func_b(y): Some
func_b code
print('inside func_b')
return y Some
func_c code
def func_c(f, z):
print('inside func_c') None
return f(z)
print(func_a()) 7
print(5 + func_b(2))
print(func_c(func_b, 3))
50
6.100L Lecture 8
FUNCTIONS AS PARAMETERS
6.100L Lecture 8
FUNCTIONS AS PARAMETERS
6.100L Lecture 8
FUNCTIONS AS PARAMETERS
54
6.100L Lecture 8
SUMMARY
55
6.100L Lecture 8
MITOpenCourseWare
https://ocw.mit.edu
For information about citing these materials or our Terms ofUse,visit: https://ocw.mit.edu/terms.
56