DECOMPOSITION,
ABSTRACTION, FUNCTIONS
(download slides and .py files to follow along)
6.100L Lecture 7
Ana Bell
1
AN EXAMPLE: the SMARTPHONE
A black box, and can be viewed in terms of
Its inputs
Its outputs
How outputs are related to inputs, without any
knowledge of its internal workings
Implementation is “opaque” (or black)
6.100L Lecture 7
AN EXAMPLE: the SMARTPHONE
ABSTRACTION
User doesn’t know the details of how it
works
We don’t need to know how something works in
order to know how to use it
User does know the interface
Device converts a sequence of screen touches and
sounds into expected useful functionality
Know relationship between input and output
6.100L Lecture 7
ABSTRACTION ENABLES
DECOMPOSITION
100’s of distinct parts
Designed and made by different
companies
Do not communicate with each other,
other than specifications for components
May use same subparts as others
Each component maker has to know
how its component interfaces to other
components
Each component maker can solve sub-
problems independent of other parts,
so long as they provide specified inputs
True for hardware and for software 4
6.100L Lecture 7
BIG IDEA
Apply
abstraction (black box) and
decomposition (split into self-contained parts)
to programming!
6.100L Lecture 7
SUPPRESS DETAILS with
ABSTRACTION
In programming, want to think of piece of code as black box
Hide tedious coding details from the user
Reuse black box at different parts in the code (no copy/pasting!)
Coder creates details, and designs interface
User does not need or want to see details
6.100L Lecture 7
SUPPRESS DETAILS with
ABSTRACTION
Coder achieves abstraction with a function (or procedure)
You’ve already been using functions!
A function lets us capture code within a black box
Once we create function, it will produce an output from inputs, while
hiding details of how it does the computation
max(1,4)
abs(-3)
len("mom's spaghetti")
6.100L Lecture 7
SUPPRESS DETAILS with
ABSTRACTION
A function has specifications, captured using docstrings
Think of a docstring as “contract” between coder and user:
If user provides input that satisfies stated conditions, function will
produce output according to specs, including indicated side effects
Not typically enforced in Python (we’ll see assertions later), but user
relies on coder’s work satisfying the contract
abs(-3)
6.100L Lecture 7
CREATE STRUCTURE with
DECOMPOSITION
Given the idea of black box abstraction, use it to divide code
into modules that are:
Self-contained
Intended to be reusable
Modules are used to:
Break up code into logical pieces
Keep code organized
Keep code coherent (readable and understandable)
In this lecture, achieve decomposition with functions
In a few lectures, achieve decomposition with classes
Decomposition relies on abstraction to enable construction of
complex modules from simpler ones
9
6.100L Lecture 7
FUNCTIONS
Reusable pieces of code, called functions or procedures
Capture steps of a computation so that we can use with any
input
A function is just some code written in a special, reusable way
10
6.100L Lecture 7
FUNCTIONS
Defining a function tells Python some code now exists in
memory
Functions are only useful when they are run (“called” or
“invoked”)
You write a function once but can run it many times!
Compare to code in a file
It doesn’t run when you load the file
It runs when you hit the run button
11
6.100L Lecture 7
FUNCTION CHARACTERISTICS
Has a name
(think: variable bound to a function object)
Has (formal) parameters (0 or more)
The inputs
Has a docstring (optional but recommended)
A comment delineated by """ (triple quotes) that provides a
specification for the function – contract relating output to input
Has a body, a set of instructions to execute when function is
called
Returns something
Keyword return
12
6.100L Lecture 7
HOW to WRITE a FUNCTION
def is_even( i ):
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
if i%2 == 0:
return True
else:
return False
13
6.100L Lecture 7
HOW TO THINK ABOUT WRITING
A FUNCTION
What is the problem?
Given an int, call it i, want to know if it is even
Use this to write the function name and specs
def is_even( i ):
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
14
6.100L Lecture 7
HOW TO THINK ABOUT WRITING
A FUNCTION
How to solve the problem?
Can check that remainder when divided by 2 is 0
Think about what value you need to give back
def is_even( i ):
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
if i%2 == 0:
return True
else:
return False
15
6.100L Lecture 7
HOW TO THINK ABOUT WRITING
A FUNCTION
Can you make the code cleaner?
i%2 is a Boolean that evaluates to True/False already
def is_even( i ):
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
return i%2 == 0
16
6.100L Lecture 7
BIG IDEA
At this point, all we’ve
done is make a function
object
17
6.100L Lecture 7
HOW TO CALL (INVOKE) A
FUNCTION
is_even(3)
is_even(8)
That’s all!
18
6.100L Lecture 7
HOW TO CALL (INVOKE) A
FUNCTION
is_even(3)
is_even(8)
That’s all!
19
6.100L Lecture 7
ALL TOGETHER IN A FILE
This code might be in one file
def is_even( i ):
return i%2 == 0
is_even(3)
20
6.100L Lecture 7
WHAT HAPPENS when you CALL a
FUNCTION?
Python replaces:
formal parameters in function def with values from function call
i replaced with 3
def is_even( i ):
return i%2 == 0
is_even(3)
21
6.100L Lecture 7
WHAT HAPPENS when you CALL a
FUNCTION?
Python replaces:
formal parameters in function def with values from function call
i replaced with 3
Python executes expressions in the body of the function
return 3%2 == 0
def is_even( i ):
return i%2 == 0
is_even(3)
22
6.100L Lecture 7
WHAT HAPPENS when you CALL a
FUNCTION?
Python replaces:
formal parameters in function def with values from function call
i replaced with 3
def is_even( i ):
return i%2 == 0
is_even(3)
print(is_even(3))
23
6.100L Lecture 7
BIG IDEA
A function’s code
only runs when you
call (aka invoke) the function
24
6.100L Lecture 7
YOU TRY IT!
Write code that satisfies the following specs
def div_by(n, d):
""" n and d are ints > 0
Returns True if d divides n evenly and False otherwise """
Test your code with:
n = 10 and d = 3
n = 195 and d = 13
25
6.100L Lecture 7
ZOOMING OUT
(no functions)
a = 3 Program Scope
b = 4 3
a
c = a+b
b 4
c 7
26
6.100L Lecture 7
ZOOMING OUT
This is my “black box”
def is_even( i ): Program Scope
print("inside is_even") function
Some
is_even
return i%2 == 0 object
code
a = is_even(3)
b = is_even(10)
c = is_even(123456)
This is me telling my black box to do
something
27
6.100L Lecture 7
ZOOMING OUT
This is my “black box”
def is_even( i ): Program Scope
print("inside is_even") function
Some
is_even
return i%2 == 0 object
code
a False
a = is_even(3)
b = is_even(10)
c = is_even(123456)
One function call
28
6.100L Lecture 7
ZOOMING OUT
This is my “black box”
def is_even( i ): Program Scope
print("inside is_even") function
Some
is_even
return i%2 == 0 object
code
a False
b True
a = is_even(3)
b = is_even(10)
c = is_even(123456)
One function call
29
6.100L Lecture 7
ZOOMING OUT
This is my “black box”
def is_even( i ): Program Scope
print("inside is_even") function
Some
is_even
return i%2 == 0 object
code
a False
b True
a = is_even(3)
b = is_even(10) c True
c = is_even(123456)
One function call
30
6.100L Lecture 7
INSERTING FUNCTIONS IN CODE
Remember how expressions are replaced with the value?
The function call is replaced with the return value!
print("Numbers between 1 and 10: even or odd")
for i in range(1,10):
if is_even(i):
print(i, "even")
else:
print(i, "odd")
31
6.100L Lecture 7
ANOTHER EXAMPLE
Suppose we want to add all the odd integers between (and
including) a and b
def sum_odd(a, b):
What is the input?
# your code here
Values for a and b
return sum_of_odds
What is the output?
The sum_of_odds
32
6.100L Lecture 7
BIG IDEA
Don’t write code right
away!
33
6.100L Lecture 7
PAPER FIRST
Suppose we want to add all the odd integers between (and
including) a and b
def sum_odd(a, b):
Start with a simple
# your code here
example on paper
return sum_of_odds
Systematically solve
the example
34
6.100L Lecture 7
SIMPLE TEST CASE
Suppose we want to add all the odd integers between (and
including) a and b
def sum_odd(a, b):
Start with a simple
# your code here
example on paper
return sum_of_odds
a = 2 and b = 4
sum_of_odds should be 3
2 3 4
a b 35
6.100L Lecture 7
MORE COMPLEX TEST CASE
Suppose we want to add all the odd integers between (and
including) a and b
def sum_odd(a, b):
Start with a simple
# your code here
example on paper
return sum_of_odds
a = 2 and b = 7
sum_of_odds should be 15
2 3 4 5 6 7
a b 36
6.100L Lecture 7
2 3 4
SOLVE SIMILAR PROBLEM
a b
Start by looking at each number between (and including) a and b
A similar problem that is
easier that you know
how to do? def sum_odd(a, b):
Add ALL numbers between # your code here
(and including) a and b return sum_of_odds
Start with this
37
6.100L Lecture 7
2 3 4
CHOOSE BIG-PICTURE STRUCTURE
a b
Add ALL numbers between
(and including) a and b
It’s a loop
while or for? def sum_odd(a, b):
Your choice # your code here
return sum_of_odds
38
6.100L Lecture 7
WRITE the LOOP 2 3 4
(for adding all numbers)
a b
for LOOP while LOOP
def sum_odd(a, b): def sum_odd(a, b):
for i in range(a, b): i = a
# do something while i <= b:
return sum_of_odds # do something
i += 1
return sum_of_odds
39
6.100L Lecture 7
DO the SUMMING 2 3 4
(for adding all numbers)
a b
for LOOP while LOOP
def sum_odd(a, b): def sum_odd(a, b):
for i in range(a, b): i = a
sum_of_odds += i while i <= b:
return sum_of_odds sum_of_odds += i
i += 1
return sum_of_odds
40
6.100L Lecture 7
INITIALIZE the SUM 2 3 4
(for adding all numbers)
a b
for LOOP while LOOP
def sum_odd(a, b): def sum_odd(a, b):
sum_of_odds = 0 sum_of_odds = 0
for i in range(a, b): i = a
sum_of_odds += i while i <= b:
return sum_of_odds sum_of_odds += i
i += 1
return sum_of_odds
41
6.100L Lecture 7
TEST! 2 3 4
(for adding all numbers)
a b
for LOOP while LOOP
def sum_odd(a, b): def sum_odd(a, b):
sum_of_odds = 0 sum_of_odds = 0
for i in range(a, b): i = a
sum_of_odds += i while i <= b:
return sum_of_odds sum_of_odds += i
i += 1
return sum_of_odds
print(sum_odd(2,4))
print(sum_odd(2,4))
42
6.100L Lecture 7
WEIRD RESULTS… 2 3 4
(for adding all numbers)
a b
for LOOP while LOOP
def sum_odd(a, b): def sum_odd(a, b):
sum_of_odds = 0 sum_of_odds = 0
for i in range(a, b): i = a
sum_of_odds += i while i <= b:
return sum_of_odds sum_of_odds += i
i += 1
return sum_of_odds
print(sum_odd(2,4))
print(sum_odd(2,4)) 9
5
43
6.100L Lecture 7
DEBUG! aka ADD PRINT STATEMENTS 2 3 4
(for adding all numbers)
a b
for LOOP while LOOP
def sum_odd(a, b): def sum_odd(a, b):
sum_of_odds = 0 sum_of_odds = 0
for i in range(a, b): i = a
sum_of_odds += i while i <= b:
print(i, sum_of_odds) sum_of_odds += i
return sum_of_odds print(i, sum_of_odds)
i += 1
22 return sum_of_odds
22
35 35
print(sum_odd(2,4)) 49
print(sum_odd(2,4)) 9
5
44
6.100L Lecture 7
FIX for LOOP END INDEX 2 3 4
(for adding all numbers)
a b
for LOOP while LOOP
def sum_odd(a, b): def sum_odd(a, b):
sum_of_odds = 0 sum_of_odds = 0
for i in range(a, b+1): i = a
sum_of_odds += i while i <= b:
print(i, sum_of_odds) sum_of_odds += i
return sum_of_odds print(i, sum_of_odds)
i += 1
return sum_of_odds
print(sum_odd(2,4))
print(sum_odd(2,4)) 9
9
45
6.100L Lecture 7
2 3 4
ADD IN THE ODD PART!
a b
for LOOP while LOOP
def sum_odd(a, b): def sum_odd(a, b):
sum_of_odds = 0 sum_of_odds = 0
for i in range(a, b+1): i = a
if i%2 == 1: while i <= b:
sum_of_odds += i if i%2 == 1:
print(i, sum_of_odds) sum_of_odds += i
return sum_of_odds print(i, sum_of_odds)
i += 1
print(sum_odd(2,4)) return sum_of_odds
print(sum_odd(2,4)) 3
3
46
6.100L Lecture 7
BIG IDEA
Solve a simpler problem
first.
Add functionality to the code later.
47
6.100L Lecture 7
TRY IT ON ANOTHER 2 3 4 5 6 7
EXAMPLE
a b
for LOOP while LOOP
def sum_odd(a, b): def sum_odd(a, b):
sum_of_odds = 0 sum_of_odds = 0
for i in range(a, b+1): i = a
if i%2 == 1: while i <= b:
sum_of_odds += i if i%2 == 1:
return sum_of_odds sum_of_odds += i
i += 1
return sum_of_odds
print(sum_odd(2,7))
print(sum_odd(2,7)) 15
15
48
6.100L Lecture 7
PYTHON TUTOR
Also a great debugging tool
49
6.100L Lecture 7
BIG IDEA
Test code often.
Use prints to debug.
50
6.100L Lecture 7
YOU TRY IT!
Write code that satisfies the following specs
def is_palindrome(s):
""" s is a string
Returns True if s is a palindrome and False otherwise
"""
For example:
If s = "222" returns True
If s = "2222" returns True
If s = "abc" returns False
51
6.100L Lecture 7
SUMMARY
Functions allow us to suppress detail from a user
Functions capture computation within a black box
A programmer writes functions with
0 or more inputs
Something to return
A function only runs when it is called
The entire function call is replaced with the return value
Think expressions! And how you replace an entire expression with the
value it evaluates to.
52
6.100L Lecture 7
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.
53