You are on page 1of 2

Functions_HigherOrder

Ibrahim Abou-Faycal

#
EECE-231
#
Introduction to Computation & Programming with Applications
#
Functions - Handling Other Functions

Reading: [Guttag, Sections 4.1,4.2, 4.5, and 5.3] Material in these slides is based on
• Slides of EECE-230C & EECE-230 MSFEA, AUB
• [Guttag, Chapter 4]
• [MIT OpenCourseWare, 6.0001, Lecture 4, Fall 2016]

0.1 Function handling other functions


1. Function defined in another function
2. High order functions: a function is called a high order function if:
• it returns another function, or
• it takes another function as input argument

0.1.1 Function defined in another function


[ ]: def f(x):
def g(y):
return y+1
z = g(x)
return z*z

print(f(1))
# We can't call g() from outside f !
print(g(2))

1
0.1.2 Function returning another function
Key concept: in Python, functions are objects
[ ]: def f(b):
if b==1:
def g(y):
return y
else:
def g(y):
return y*y
return g

print( f(1)(10) )

[ ]: print(f(2)(25))

0.1.3 Function taking another function as input argument


In Python, functions are objects
[ ]: def linear(x):
return x
def square(x):
return x*x

def findSum(n,p):
x = 0
for i in range(1,n+1):
x = x + p(i)
return x

print(findSum(10, linear))

[ ]: print(findSum(10, square))

You might also like