0% found this document useful (0 votes)
38 views56 pages

Cours Mit

Uploaded by

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

Cours Mit

Uploaded by

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

FUNCTIONS as OBJECTS

(download slides and .py files to follow along)


6.100L Lecture 8
Ana Bell

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

 A function always returns something

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

 Python returns the value None, if no return given


 Represents the absence of a value
 If invoked in shell, nothing is printed
 No static semantic error generated
3

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

 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, but  code inside function can be
after return statement, executed after a print
not executed statement
 has a value associated  has a value associated with
with it, given to function it, outputted to the console
caller
 print expression itself returns
None value
6

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))

 Write a function that calls this one!

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 """

Use bisection_root we already wrote to get an approximation


for the sqrt of an integer.
For example: print(count_nums_with_sqrt_close_to(10, 0.1))
prints 4 because all these integers have a sqrt within 0.1
 sqrt of 99 is 9.949699401855469
 sqrt of 100 is 9.999847412109375
 sqrt of 101 is 10.049758911132812
 sqrt of 102 is 10.099456787109375

10

6.100L Lecture 8
ZOOMING OUT

This is my “black box”

def sum_odd(a, b): Program Scope


sum_of_odds = 0
for i in range(a, b+1): sum_odd Some
function
if i%2 == 1: code
object
sum_of_odds += i low 2
return sum_of_odds
high 7
low = 2
high = 7
my_sum = sum_odd(low, high) my_sum

One function call

11

6.100L Lecture 8
ZOOMING OUT

def sum_odd(a, b): Program Scope


sum_of_odds = 0
for i in range(a, b+1): sum_odd Some
function
if i%2 == 1: code
object
sum_of_odds += i low 2
return sum_of_odds
high 7
low = 2
high = 7
my_sum = sum_odd(low, high) my_sum

12

6.100L Lecture 8
ZOOMING OUT

This is my “black box”

def sum_odd(a, b): Program Scope


sum_of_odds = 0
for i in range(a, b+1): sum_odd Some
function
if i%2 == 1: code
object
sum_of_odds += i low 2
return sum_of_odds
high 7
low = 2
high = 7 15
my_sum = sum_odd(low, high) my_sum

15

13

6.100L Lecture 8
FUNCTION SCOPE

14

6.100L Lecture 8
UNDERSTANDING FUNCTION
CALLS

 How does Python execute a function call?


 How does Python know what value is associated with a variable
name?
 It creates a new environment with every function call!
 Like a mini program that it needs to complete
 The mini program runs with assigning its parameters to some inputs
 It does the work (aka the body of the function)
 It returns a value
 The environment disappears after it returns the value

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

 Formal parameters get bound to the value of input parameters


 Scope is a mapping of names to objects
 Defines context in which body is evaluated
 Values of variables given by bindings of names
 Expressions in body of function evaluated wrt this new scope
def f( x ):
x = x + 1
print('in f(x): x =', x)
return x

xy = 3
z = f( y
x )
17

6.100L Lecture 8
VARIABLE SCOPE
after evaluating def

This is my “black box”

def f( x ): Global scope


x = x + 1
function
Some
print('in f(x): x =', x) f object
code
return x

x = 3
z = f( x )
18

6.100L Lecture 8
VARIABLE SCOPE
after exec 1st assignment

This is my “black box”

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 )
19

6.100L Lecture 8
VARIABLE SCOPE
after f invoked

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 )
20

6.100L Lecture 8
VARIABLE SCOPE
after f invoked

def f( x ): Global scope f scope


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

6.100L Lecture 8
VARIABLE SCOPE
eval body of f in f’s scope

in f(x): x = 4 printed out

def f( x ): Global scope f scope


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

6.100L Lecture 8
VARIABLE SCOPE
during return

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 returns 4
x = 3
z = f( x )
23

6.100L Lecture 8
VARIABLE SCOPE
after exec 2nd assignment

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
z
24

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

 Inside a function, can access a variable defined outside


 Inside a function, cannot modify a variable defined outside
(can by using global variables, but frowned upon)
 Use the Python Tutor to step through these!

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


x = 1 print(x) x += 1
x += 1 print(x + 1)
print(x) x = 5
x = 5 h(x)
x = 5 g(x) print(x)
f(x) print(x)
print(x)
5
2 6 Error
5 5

26

6.100L Lecture 8
FUNCTIONS as
ARGUMENTS

27

6.100L Lecture 8
HIGHER ORDER PROCEDURES

 Objects in Python have a type


 int, float, str, Boolean, NoneType, function
 Objects can appear in RHS of assignment statement
 Bind a name to an object
 Objects
 Can be used as an argument to a procedure
 Can be returned as a value from a procedure
 Functions are also first class objects!
 Treat functions just like the other types
 Functions can be arguments to another function
 Functions can be returned by another function

28

6.100L Lecture 8
OBJECTS IN A PROGRAM

function
my_func object with
some code
is_even

def is_even(i): r int object 2


return i%2 == 0
float object
pi
r = 2 3.14285714

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 calc(op, x, y):


return op(x,y)

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

def calc(op, x, y):


return op(x,y)
Program Scope
def add(a,b):
return a+b calc function
Some
object
code
def div(a,b):
if b != 0: add function
Some
return a/b
object
code
print("Denom was 0.")
div function
Some
object
code
res = calc(add, 2, 3)

res

32

6.100L Lecture 8
CREATE calc SCOPE

def calc(op, x, y):


return op(x,y)
Program Scope calc scope
def add(a,b):
return a+b calc function
Some
object
code
def div(a,b):
if b != 0: add function
Some
return a/b
object
code
print("Denom was 0.")
div function
Some
object
code
res = calc(add, 2, 3)

res

33

6.100L Lecture 8
MATCH FORMAL PARAMS in calc

def calc(op, x, y):


return op(x,y)
Program Scope calc scope
def add(a,b):
return a+b calc function
Some op add
object
code
def div(a,b):
if b != 0: add function
Some x 2
return a/b
object
code
print("Denom was 0.")
div function
Some y 3
object
code
res = calc(add, 2, 3)

res

34

6.100L Lecture 8
FIRST (and only) LINE IN calc

def calc(op, x, y):


return op(x,y)
Program Scope calc scope
def add(a,b):
return a+b calc function
Some op add
object
code
def div(a,b):
if b != 0: add function
Some x 2
return a/b
object
code
print("Denom was 0.")
div function
Some y 3
object
code
res = calc(add, 2, 3)

res

35

6.100L Lecture 8
CREATE SCOPE OF add

def calc(op, x, y):


return op(x,y)
Program Scope calc scope add scope
def add(a,b):
return a+b calc function
Some op add
object
code
def div(a,b):
if b != 0: add function
Some x 2
return a/b
object
code
print("Denom was 0.")
div function
Some y 3
object
code
res = calc(add, 2, 3)

res

36

6.100L Lecture 8
MATCH FORMAL PARAMS IN add

def calc(op, x, y):


return op(x,y)
Program Scope calc scope add scope
def add(a,b):
return a+b calc function
Some op a
add 2
object
code
def div(a,b):
if b != 0: add function
Some x 2 b 3
return a/b
object
code
print("Denom was 0.")
div function
Some y 3
object
code
res = calc(add, 2, 3)

res

37

6.100L Lecture 8
EXECUTE LINE OF add

def calc(op, x, y):


return op(x,y)
Program Scope calc scope add scope
def add(a,b):
return a+b calc function
Some op a
add 2
object
code
def div(a,b):
if b != 0: add function
Some x 2 b 3
return a/b
object
code
print("Denom was 0.")
div function
Some y 3
object
code
res = calc(add, 2, 3)

res
returns 5
38

6.100L Lecture 8
REPLACE FUNC CALL WITH RETURN

def calc(op, x, y):


return op(x,y)
Program Scope calc scope
def add(a,b):
return a+b calc function
Some op add
object
code
def div(a,b):
if b != 0: add function
Some x 2
return a/b
object
code
print("Denom was 0.")
div function
Some y 3
object
code
res = calc(add, 2, 3)

res

39

6.100L Lecture 8
EXECUTE LINE OF calc

def calc(op, x, y):


return op(x,y)
Program Scope calc scope
def add(a,b):
return a+b calc function
Some op add
object
code
def div(a,b):
if b != 0: add function
Some x 2
return a/b
object
code
print("Denom was 0.")
div function
Some y 3
object
code
res = calc(add, 2, 3)

res
returns 5
40

6.100L Lecture 8
REPLACE FUNC CALL WITH RETURN

def calc(op, x, y):


return op(x,y)
Program Scope
def add(a,b):
return a+b calc function
Some
object
code
def div(a,b):
if b != 0: add function
Some
return a/b
object
code
print("Denom was 0.")
div function
Some
object
code
res = calc(add, 2, 3)

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)

What is the value of res and what gets printed?

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

Global scope func_a 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))
44

6.100L Lecture 8
FUNCTIONS AS PARAMETERS

Global scope func_a 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') None


return f(z)
print(func_a())
print(5 + func_b(2))
print(func_c(func_b, 3))
45

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

Global scope func_b scope


def func_a(): Some
func_a y 2
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())
print(5 + func_b(2))
print(func_c(func_b, 3))
47

6.100L Lecture 8
FUNCTIONS AS PARAMETERS

Global scope func_b scope


def func_a(): Some
func_a y 2
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())
print(5 + func_b(2))
print(func_c(func_b, 3))
48

6.100L Lecture 8
FUNCTIONS AS PARAMETERS

Global scope func_b scope


def func_a(): Some
func_a y 2
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 returns 2
print(5 + func_b(2))
print(func_c(func_b, 3))
49

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

Global scope func_c scope


def func_a(): Some
func_a f func_b
print('inside func_a') code
def func_b(y): Some z
3
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))
51

6.100L Lecture 8
FUNCTIONS AS PARAMETERS

Global scope func_c scope


def func_a(): Some
func_a f func_b
print('inside func_a') code
def func_b(y): Some z
3
func_b code
print('inside func_b')
return y Some 3
func_c code
def func_c(f, z):
print('inside func_c') None returns 3 func_b scope
return f(z)
print(func_a()) y 3
7
print(5 + func_b(2))
print(func_c(func_b, 3))
52

6.100L Lecture 8
FUNCTIONS AS PARAMETERS

Global scope func_c scope


def func_a(): Some
func_a f func_b
print('inside func_a') code
def func_b(y): Some z
3
func_b code
print('inside func_b')
return y Some 3
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)) 3
53
returns 3
6.100L Lecture 8
YOU TRY IT!
 Write a function that meets these specs.
def apply(criteria,n):
"""
* criteria is a func that takes in a number and returns a bool
* n is an int
Returns how many ints from 0 to n (inclusive) match
the criteria (i.e. return True when run with criteria)
"""

54

6.100L Lecture 8
SUMMARY

 Functions are first class objects


 They have a type
 They can be assigned as a value bound to a name
 They can be used as an argument to another procedure
 They can be returned as a value from another procedure
 Have to be careful about environments
 Main program runs in the global environment
 Function calls each get a new temporary environment
 This enables the creation of concise, easily read code

55

6.100L Lecture 8
MITOpenCourseWare
https://ocw.mit.edu

6.100L Introduction to Computer Science and Programming Using Python


Fall 2022

For information about citing these materials or our Terms ofUse,visit: https://ocw.mit.edu/terms.

56

You might also like