Basic Python
Basic Python
1
TODAY
Course info
What is computation
Python basics
Mathematical operations
Python variables and types
NOTE: slides and code files up before each lecture
Highly encourage you to download them before class
Take notes and run code files when I do
Do the in-class “You try it” breaks
Class will not be recorded
Class will be live-Zoomed for those sick/quarantine
6.100L Lecture 1
WHY COME TO CLASS?
6.100L Lecture 1
OFFICE
PSETS
HOURS
OPTIONAL
PIAZZA (practice)
PROBLEM
SOLVING MANDATORY
FINGER
PRACTICE
EXERCISES
LECTURES
KNOWLEDGE PROGRAMMING
OF CONCEPTS SKILL
RECITATION
EXAMS
6.100L Lecture 1
LET’S GOOOOO!
6
TYPES of KNOWLEDGE
6.100L Lecture 1
NUMERICAL EXAMPLE
6.100L Lecture 1
NUMERICAL EXAMPLE
6.100L Lecture 1
NUMERICAL EXAMPLE
10
6.100L Lecture 1
WE HAVE an ALGORITHM
11
6.100L Lecture 1
ALGORITHMS are RECIPES /
RECIPES are ALGORITHMS
Bake cake from a box
1) Mix dry ingredients
2) Add eggs and milk
3) Pour mixture in a pan
4) Bake at 350F for 5 minutes
5) Stick a toothpick in the cake
6a) If toothpick does not come out clean, repeat step 4 and 5
6b) Otherwise, take pan out of the oven
7) Eat
12
6.100L Lecture 1
COMPUTERS are MACHINES that
EXECUTE ALGORITHMS
Two things computers do:
Performs simple operations
100s of billions per second!
Remembers results
100s of gigabytes of storage!
What kinds of calculations?
Built-in to the machine, e.g., +
Ones that you define as the programmer
The BIG IDEA here?
13
6.100L Lecture 1
A COMPUTER WILL ONLY DO
WHAT YOU TELL IT TO DO
14
6.100L Lecture 1
COMPUTERS are MACHINES that
EXECUTE ALGORITHMS
Fixed program computer
Fixed set of algorithms
What we had until 1940’s
Stored program computer
Machine stores and executes instructions
Key insight: Programs are no different from other kinds of data
15
6.100L Lecture 1
STORED PROGRAM COMPUTER
16
6.100L Lecture 1
MEMORY
CONTROL ARITHMETIC
UNIT LOGIC UNIT
program counter do primitive ops
INPUT OUTPUT
17
6.100L Lecture 1
3456 3 7889 5
3457 4 7890 2
3458
3459 True
7891
7892 MEMORY
3460 7893
3461 False 7894
INPUT OUTPUT
18
6.100L Lecture 1
3456 3 7889 5
3457 4 7890 2
3458
3459 True
7891
7892 MEMORY
3460 7893
3461 False 7894
INPUT OUTPUT
19
6.100L Lecture 1
3456 3 7889 5
3457 4 7890 2
3458
3459
7
True
7891
7892 MEMORY
3460 7893
3461 False 7894
INPUT OUTPUT
20
6.100L Lecture 1
3456 3 7889 5
3457 4 7890 2
3458
3459
7
True
7891
7892 MEMORY
3460 7893
3461 False 7894
INPUT OUTPUT
21
6.100L Lecture 1
3456 3 7889 5
3457 4 7890 2
3458
3459
7
True
7891
7892
7
MEMORY
3460 7893
3461 False 7894
INPUT OUTPUT
22
6.100L Lecture 1
3456 3 7889 5
3457 4 7890 2
3458
3459
7
True
7891
7892
7
MEMORY
3460 7893
3461 False 7894
INPUT OUTPUT
23
6.100L Lecture 1
3456 3 7889 5
3457 4 7890 2
3458
3459
7
True
7891
7892
7
MEMORY
3460 7893
3461 False 7894
INPUT OUTPUT
True
24
6.100L Lecture 1
BASIC PRIMITIVES
6.100L Lecture 1
ASPECTS of LANGUAGES
Primitive constructs
English: words
Programming language: numbers, strings, simple operators
26
6.100L Lecture 1
ASPECTS of LANGUAGES
Syntax
English: "cat dog boy" not syntactically valid
"cat hugs boy" syntactically valid
Programming language: "hi"5 not syntactically valid
"hi"*5 syntactically valid
27
6.100L Lecture 1
ASPECTS of LANGUAGES
28
6.100L Lecture 1
ASPECTS of LANGUAGES
29
6.100L Lecture 1
WHERE THINGS GO WRONG
Syntactic errors
Common and easily caught
Static semantic errors
Some languages check for these before running
program
Can cause unpredictable behavior
No linguistic errors, but different meaning
than what programmer intended
Program crashes, stops running
Program runs forever
Program gives an answer, but it’s wrong!
30
6.100L Lecture 1
PYTHON PROGRAMS
31
6.100L Lecture 1
PROGRAMMING ENVIRONMENT:
ANACONDA
Code Editor
Shell / Console
32
6.100L Lecture 1
OBJECTS
33
6.100L Lecture 1
OBJECTS
34
6.100L Lecture 1
SCALAR OBJECTS
>>> type(5)
int
>>> type(3.0)
float
35
6.100L Lecture 1
int float
0, 1, 2, …
0.0, …, 0.21, …
300, 301 …
1.0, …, 3.14, …
-1, -2, -3, …
-1.22, …, -500.0 , …
-400, -401, …
bool NoneType
True
False None
36
6.100L Lecture 1
YOU TRY IT!
In your console, find the type of:
1234
8.99
9.0
True
False
37
6.100L Lecture 1
TYPE CONVERSIONS (CASTING)
38
6.100L Lecture 1
YOU TRY IT!
In your console, find the type of:
float(123)
round(7.9)
float(round(7.2))
int(7.2)
int(7.9)
39
6.100L Lecture 1
EXPRESSIONS
40
6.100L Lecture 1
BIG IDEA
Replace complex
expressions by ONE value
Work systematically to evaluate the expression.
41
6.100L Lecture 1
EXAMPLES
>>> 3+2
5
>>> (4+2)*6-1
35
>>> type((4+2)*6-1)
int
>>> float((4+2)*6-1)
35.0
42
6.100L Lecture 1
YOU TRY IT!
In your console, find the values of the following expressions:
(13-4) / (12*12)
type(4*3)
type(4.0*3)
int(1/2)
43
6.100L Lecture 1
OPERATORS on int and float
44
6.100L Lecture 1
SIMPLE OPERATIONS
**
45
6.100L Lecture 1
SO MANY OBJECTS, what to do
with them?!
temp = 100.4
a= 2
go = True
b= -0.3
x= 123 flag = False
n= 17
small = 0.001
46
6.100L Lecture 1
VARIABLES
CS variables
Is bound to one single value at a given time a = b + 1
Can be bound to an expression
(but expressions evaluate to one value!) m = 10
F = m*9.98
47
6.100L Lecture 1
BINDING VARIABLES to VALUES
pi = 355/113
Step 1: Compute the value on the right hand side (the VALUE)
Value stored in computer memory
Step 2: Store it (bind it) to the left hand side (the VARIABLE)
Retrieve value associated with name by invoking the name
(typing it out)
48
6.100L Lecture 1
YOU TRY IT!
Which of these are allowed in Python? Type them in the
console to check.
x = 6
6 = x
x*y = 3+4
xy = 3+4
49
6.100L Lecture 1
ABSTRACTING EXPRESSIONS
6.100L Lecture 1
WHAT IS BEST CODE STYLE?
#do calculations
a = 355/113 *(2.2**2)
c = 355/113 *(2.2*2)
p = 355/113
r = 2.2
#multiply p with r squared
a = p*(r**2)
#multiply p with r times 2
c = p*(r*2)
6.100L Lecture 1
CHANGE BINDINGS
52
6.100L Lecture 1
BIG IDEA
Lines are evaluated one
after the other
No skipping around, yet.
We’ll see how lines can be skipped/repeated later.
53
6.100L Lecture 1
YOU TRY IT!
These 3 lines are executed in order. What are the values of
meters and feet variables at each line in the code?
meters = 100
feet = 3.2808 * meters
meters = 200
ANSWER:
Let’s use PythonTutor to figure out what is going on
Follow along with this Python Tutor LINK
Where did we tell Python to (re)calculate feet?
54
6.100L Lecture 1
YOU TRY IT!
Swap values of x and y without binding the numbers directly.
Debug (aka fix) this code.
x = 1 1
y = 2 x
2
y
y = x
x = y
Python Tutor to the rescue?
ANSWER:
1
x
2
y
temp
55
6.100L Lecture 1
SUMMARY
Objects
Objects in memory have types.
Types tell Python what operations you can do with the objects.
Expressions evaluate to one value and involve objects and operations.
Variables bind names to objects.
= sign is an assignment, for ex. var = type(5*4)
Programs
Programs only do what you tell them to do.
Lines of code are executed in order.
Good variable names and comments help you read code later.
56
6.100L Lecture 1
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
57
STRINGS, INPUT/OUTPUT,
and BRANCHING
(download slides and .py files to follow along)
6.100L Lecture 2
Ana Bell
1
pi = 3.14 3.14
RECAP radius = 2.2
pi
2.2
area = pi*(radius**2)
radius
area 3.2
radius = radius+1
15.1976
var = type(5*4) var int
Objects
Objects in memory have types.
Types tell Python what operations you can do with the objects.
Expressions evaluate to one value and involve objects and operations.
Variables bind names to objects.
= sign is an assignment, for ex. var = type(5*4)
Programs
Programs only do what you tell them to do.
Lines of code are executed in order.
Good variable names and comments help you read code later.
2
6.100L Lecture 2 2
STRINGS
6.100L Lecture 2 3
STRINGS
silly = a * 3 c "memyself"
d "me myself"
silly "mememe"
6.100L Lecture 2 4
YOU TRY IT!
What’s the value of s1 and s2?
b = ":"
c = ")"
s1 = b + 2*c
f = "a"
g = " b"
h = "3"
s2 = (f+g)*int(h)
6.100L Lecture 2 5
STRING OPERATIONS
s = "abc"
len(s) evaluates to 3
chars = len(s)
6.100L Lecture 2 7
SLICING to get
ONE CHARACTER IN A STRING
Square brackets used to perform indexing
into a string to get the value at a certain
index/position
s = "abc"
index:
index:
0 1 2 indexing always starts at 0
-3 -2 -1 index of last element is len(s) - 1 or -1
s[0] evaluates to "a"
s[1] evaluates to "b"
s[2] evaluates to "c"
s[3] trying to index out of
bounds, error
s[-1] evaluates to "c"
s[-2] evaluates to "b"
s[-3] evaluates to "a"
7
6.100L Lecture 2 8
SLICING to get a SUBSTRING
6.100L Lecture 2 9
SLICING EXAMPLES
s = "abcdefgh"
index: 0 1 2 3 4 5 6 7
index: -8 -7 -6 -5 -4 -3 -2 -1
6.100L Lecture 2 10
YOU TRY IT!
s = "ABC d3f ghi"
s[3:len(s)-1]
s[4:0:-1]
s[6:3]
10
6.100L Lecture 2 11
IMMUTABLE STRINGS
"bar"
s
11
6.100L Lecture 2 12
BIG IDEA
If you are wondering
“what happens if”…
Just try it out in the console!
12
6.100L Lecture 2 13
INPUT/OUTPUT
13
6.100L Lecture 2 14
PRINTING
6.100L Lecture 2 15
INPUT
x = input(s)
Prints the value of the string s
User types in something and hits enter
That value is assigned to the variable x
Binds that value to a variable
text = input("Type anything: ")
print(5*text)
SHELL:
Type anything:
15
6.100L Lecture 2 17
INPUT
x = input(s)
Prints the value of the string s
User types in something and hits enter
That value is assigned to the variable x
Binds that value to a variable
text = input("Type anything: ")
print(5*text)
SHELL:
16
6.100L Lecture 2 18
INPUT
x = input(s)
Prints the value of the string s
User types in something and hits enter
That value is assigned to the variable x
Binds that value to a variable
text = input("Type anything: ")
print(5*text)
SHELL:
17
6.100L Lecture 2 19
INPUT
x = input(s)
Prints the value of the string s
User types in something and hits enter
That value is assigned to the variable x
Binds that value to a variable
text = input("Type anything: ")
print(5*text)
SHELL:
18
6.100L Lecture 2 20
INPUT
x = input(s)
Prints the value of the string s
User types in something and hits enter
That value is assigned to the variable x
Binds that value to a variable
text = input("Type anything: ")
print(5*text)
SHELL:
19
6.100L Lecture 2 21
INPUT
input always returns an str, must cast if working with numbers
num1 = input("Type a number: ")
print(5*num1)
num2 = int(input("Type a number: "))
print(5*num2)
SHELL:
num1 "3"
Type a number: 3
20
6.100L Lecture 2 22
INPUT
input always returns an str, must cast if working with numbers
num1 = input("Type a number: ")
print(5*num1)
num2 = int(input("Type a number: "))
print(5*num2)
SHELL:
num1 "3"
Type a number: 3
33333
21
6.100L Lecture 2 23
INPUT
input always returns an str, must cast if working with numbers
num1 = input("Type a number: ")
print(5*num1)
num2 = int(input("Type a number: "))
print(5*num2)
SHELL:
num1 "3"
Type a number: 3
33333
Type a number: 3
22
6.100L Lecture 2 24
INPUT
input always returns an str, must cast if working with numbers
num1 = input("Type a number: ")
print(5*num1)
num2 = int(input("Type a number: "))
print(5*num2)
SHELL:
num1 "3"
Type a number: 3
33333
num2 3
Type a number: 3
23
6.100L Lecture 2 25
INPUT
input always returns an str, must cast if working with numbers
num1 = input("Type a number: ")
print(5*num1)
num2 = int(input("Type a number: "))
print(5*num2)
SHELL:
num1 "3"
Type a number: 3
33333
num2 3
Type a number: 3
15
24
6.100L Lecture 2 26
YOU TRY IT!
Write a program that
Asks the user for a verb
Prints “I can _ better than you” where you replace _ with the verb.
Then prints the verb 5 times in a row separated by spaces.
For example, if the user enters run, you print:
I can run better than you!
run run run run run
25
6.100L Lecture 2 27
AN IMPORTANT ALGORITHM:
NEWTON’S METHOD
Finds roots of a polynomial
E.g., find g such that f(g, x) = g3 – x = 0
Algorithm uses successive approximation
𝑓𝑓(𝑔𝑔𝑔𝑔𝑔𝑔𝑔𝑔𝑔𝑔)
next_guess = guess -
𝑓𝑓′ (𝑔𝑔𝑔𝑔𝑔𝑔𝑔𝑔𝑔𝑔)
Partial code of algorithm that gets input and finds next guess
6.100L Lecture 2 29
F-STRINGS
6.100L Lecture 2 30
BIG IDEA
Expressions can be
placed anywhere.
Python evaluates them!
28
6.100L Lecture 2 32
CONDITIONS for
BRANCHING
29
6.100L Lecture 2 33
BINDING VARIABLES and VALUES
variable = value
Change the stored value of variable to value
Nothing for us to solve, computer just does the action
some_expression == other_expression
A test for equality
No binding is happening
Expressions are replaced by values and computer just does the
comparison
Replaces the entire line with True or False
30
6.100L Lecture 2 34
COMPARISON OPERATORS
i > j
i >= j
i < j
i <= j
i == j equality test, True if i is the same as j
i != j inequality test, True if i not the same as j
31
6.100L Lecture 2 35
LOGICAL OPERATORS on bool
A B A and B A or B
True True True True
True False False True
False True False True
False False False False
32
6.100L Lecture 2 36
COMPARISON EXAMPLE
pset_time = 15
sleep_time = 8
print(sleep_time > pset_time)
derive = True
drink = False
both = drink and derive
print(both)
pset_time 15
sleep_time 8
derive True
drink False
both False
33
6.100L Lecture 2 37
YOU TRY IT!
Write a program that
Saves a secret number in a variable.
Asks the user for a number guess.
Prints a bool False or True depending on whether the guess
matches the secret.
34
6.100L Lecture 2 38
WHY bool?
35
6.100L Lecture 2 40
INTERESTING ALGORITHMS
INVOLVE DECISIONS
It’s midnight
Free
food
email
36
6.100L Lecture 2 41
If right clear, If right blocked, If right and If right , front,
go right go forward front blocked, left blocked,
go left go back
37
6.100L Lecture 2 42
BRANCHING IN PYTHON
if <condition>:
<code>
<code>
...
<rest of program>
sion>
<expression>
...
else:
<expression>
<expression>
...
<rest of program>
6.100L Lecture 2 43
BRANCHING IN PYTHON
if <condition>:
<code>
<code>
...
<rest of program>
if <condition>:
<code>
<code>
...
else:
<code>
<code>
...
<rest of program>
6.100L Lecture 2 44
BRANCHING IN PYTHON
if <condition>: if <condition>:
<code> <code>
<code> <code>
... ...
<rest of program>
elif <condition>:
<code>
if <condition>: <code>
<code> ...
<code> elif <condition>:
... <code>
else: <code>
<code> ...
<code> <rest of program>
...
<rest of program>
6.100L Lecture 2 45
BRANCHING IN PYTHON
if <condition>: if <condition>: if <condition>:
<code> <code> <code>
<code> <code> <code>
... ... ...
<rest of program>
elif <condition>: elif <condition>:
<code> <code>
if <condition>: <code> <code>
<code> ... ...
<code> elif <condition>: else:
... <code> <code>
else: <code> <code>
<code> ... ...
<code> <rest of program> <rest of program>
...
<rest of program>
6.100L Lecture 2 46
BRANCHING EXAMPLE
pset_time = ???
sleep_time = ???
if (pset_time + sleep_time) > 24:
print("impossible!")
elif (pset_time + sleep_time) >= 24:
print("full schedule!")
else:
leftover = abs(24-pset_time-sleep_time)
print(leftover,"h of free time!")
print("end of day")
42
6.100L Lecture 2 47
YOU TRY IT!
Semantic structure matches visual structure
Fix this buggy code (hint, it has bad indentation)!
x = int(input("Enter a number for x: "))
y = int(input("Enter a different number for y: "))
if x == y:
print(x,"is the same as",y)
print("These are equal!")
43
6.100L Lecture 2 48
INDENTATION and NESTED
BRANCHING
Matters in Python
How you denote blocks of code
x = float(input("Enter a number for x: ")) 5 5 0
y = float(input("Enter a number for y: ")) 5 0 0
if x == y: True False True
print("x and y are equal") <- <-
if y != 0: True False
print("therefore, x / y is", x/y) <-
elif x < y: False
print("x is smaller")
else:
print("y is smaller") <-
print("thanks!") <- <- <-
44
6.100L Lecture 2 50
BIG IDEA
Practice will help you
build a mental model of
how to trace the code
Indentation does a lot of the work for you!
45
6.100L Lecture 2 51
YOU TRY IT!
What does this code print with
y=2
y = 20
y = 11
What if if x <= y: becomes elif x <= y: ?
answer = ''
x = 11
if x == y:
answer = answer + 'M'
if x >= y:
answer = answer + 'i'
else:
answer = answer + 'T'
print(answer)
46
6.100L Lecture 2 52
YOU TRY IT!
Write a program that
Saves a secret number.
Asks the user for a number guess.
Prints whether the guess is too low, too high, or the same as the secret.
47
6.100L Lecture 2 53
BIG IDEA
Debug early,
debug often.
Write a little and test a little.
Don’t write a complete program at once. It introduces too many errors.
Use the Python Tutor to step through code when you see something
unexpected!
48
6.100L Lecture 2 55
SUMMARY
6.100L Lecture 2 56
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
50
ITERATION
(download slides and .py files to follow along)
6.100L Lecture 3
Ana Bell
1
LAST LECTURE RECAP
6.100L Lecture 3
BRANCHING RECAP
if <condition>: if <condition>: if <condition>:
< code > < code > < code >
< code > < code > < code >
... ... ...
elif <condition>: elif <condition>:
if <condition>: < code > < code >
< code > < code > < code >
< code > ... ...
... elif <condition>: else:
else: < code > < code >
< code > < code > < code >
< code > ... ...
...
6.100L Lecture 3
If you keep going right, you are
stuck in the same spot forever
To exit, take a chance and go
Zelda, Lost Woods tricks you the opposite way
© Nintendo. All rights reserved. This content is excluded from our Creative
Commons license. For more information, see [Link]
if <exit right>:
<set background to woods_background>
if <exit right>:
<set background to woods_background>
if <exit right>:
<set background to woods_background>
and so on and on and on...
else:
<set background to exit_background>
else:
<set background to exit_background>
else:
<set background to exit_background>
4
6.100L Lecture 3
If you keep going right, you are
stuck in the same spot forever
To exit, take a chance and go
Zelda, Lost Woods tricks you the opposite way
© Nintendo. All rights reserved. This content is excluded from our Creative
Commons license. For more information, see [Link]
while <exit_right>:
<set background to woods_background>
<ask user which way to go>
<set background to exit_background>
6.100L Lecture 3
while LOOPS
6.100L Lecture 3
BINGE ALL EPISODES OF ONE SHOW
6.100L Lecture 3
CONTROL FLOW: while LOOPS
while <condition>:
<code>
<code>
...
<condition> evaluates to a Boolean
If <condition> is True, execute all the steps inside the
while code block
Check <condition> again
Repeat until <condition> is False
If <condition> is never False, then will loop forever!!
8
6.100L Lecture 3
while LOOP EXAMPLE
"left"
PROGRAM:
where = input("You're in the Lost Forest. Go left or right? ")
while where == "right":
where = input("You're in the Lost Forest. Go left or right? ")
print("You got out of the Lost Forest!")
6.100L Lecture 3
YOU TRY IT!
What is printed when you type "RIGHT"?
10
6.100L Lecture 3
while LOOP EXAMPLE
11
6.100L Lecture 3
while LOOP EXAMPLE
To terminate:
Hit CTRL-c or CMD-c in the shell
Click the red square in the shell
12
6.100L Lecture 3
YOU TRY IT!
Run this code and stop the infinite loop in your IDE
while True:
print("noooooo")
13
6.100L Lecture 3
BIG IDEA
while loops can repeat
code inside indefinitely!
Sometimes they need your intervention to end the program.
14
6.100L Lecture 3
YOU TRY IT!
Expand this code to show a sad face when the user entered the
while loop more than 2 times.
Hint: use a variable as a counter
where = input("Go left or right? ")
while where == "right":
where = input("Go left or right? ")
print("You got out!")
15
6.100L Lecture 3
CONTROL FLOW: while LOOPS
n = 0
while n < 5:
print(n)
n = n+1
16
6.100L Lecture 3
A COMMON PATTERN
Find 4!
i is our loop variable
factorial keeps track of the product
x = 4
i = 1
factorial = 1
while i <= x:
factorial *= i
i += 1
print(f'{x} factorial is {factorial}')
6.100L Lecture 3
for LOOPS
18
6.100L Lecture 3
ARE YOU STILL WATCHING?
Netflix while falling asleep
(it plays only 4 episodes if
you’re not paying attention)
6.100L Lecture 3
CONTROL FLOW:
while and for LOOPS
6.100L Lecture 3
STRUCTURE of for LOOPS
6.100L Lecture 3
A COMMON SEQUENCE of VALUES
for n in range(5):
print(n)
6.100L Lecture 3
A COMMON SEQUENCE of VALUES
2
for n in range(5): 3
print(n)
4
6.100L Lecture 3
range
24
6.100L Lecture 3
YOU TRY IT!
What do these print?
for i in range(1,4,1):
print(i)
for j in range(1,4,2):
print(j*2)
for me in range(4,0,-1):
print("$"*me)
25
6.100L Lecture 3
RUNNING SUM
mysum = 0 i 0
for i in range(10):
mysum += i
print(mysum)
mysum 0
26
6.100L Lecture 3
RUNNING SUM
mysum = 0 i 0
for i in range(10): 1
mysum += i
print(mysum)
mysum 0
1
27
6.100L Lecture 3
RUNNING SUM
mysum = 0 i 0
for i in range(10): 1
mysum += i 2
print(mysum)
mysum 1
3
28
6.100L Lecture 3
RUNNING SUM
mysum = 0 i 0
for i in range(10): 1
mysum += i 2
print(mysum) 3
mysum 3
6
29
6.100L Lecture 3
RUNNING SUM
mysum = 0 i 0
for i in range(10): 1
mysum += i 2
print(mysum)
…
3
mysum 36
45
30
6.100L Lecture 3
YOU TRY IT!
Fix this code to use variables start and end in the range, to get
the total sum between and including those values.
For example, if start=3 and end=5 then the sum should be 12.
mysum = 0
start = ??
end = ??
for i in range(start, end):
mysum += i
print(mysum)
31
6.100L Lecture 3
for LOOPS and range
x = 4
factorial = 1
for i in range(1, x+1, 1):
factorial *= i
print(f'{x} factorial is {factorial}')
32
6.100L Lecture 3
BIG IDEA
for loops only repeat
for however long the
sequence is
The loop variables takes on these values in order.
33
6.100L Lecture 3
SUMMARY
Looping mechanisms
while and for loops
Lots of syntax today, be sure to get lots of practice!
While loops
Loop as long as a condition is true
Need to make sure you don’t enter an infinite loop
For loops
Can loop over ranges of numbers
Can loop over elements of a string
Will soon see many other things are easy to loop over
34
6.100L Lecture 3
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
35
DECOMPOSITION,
ABSTRACTION, FUNCTIONS
(download slides and .py files to follow along)
6.100L Lecture 7
Ana Bell
1
AN EXAMPLE: the SMARTPHONE
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
10
6.100L Lecture 7
FUNCTIONS
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
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 """
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
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
a = is_even(3)
b = is_even(10)
c = is_even(123456)
One function call
28
6.100L Lecture 7
ZOOMING OUT
b True
a = is_even(3)
b = is_even(10)
c = is_even(123456)
6.100L Lecture 7
ZOOMING OUT
b True
a = is_even(3)
b = is_even(10) c True
c = is_even(123456)
6.100L Lecture 7
INSERTING FUNCTIONS IN CODE
for i in range(1,10):
if is_even(i):
print(i, "even")
else:
print(i, "odd")
31
6.100L Lecture 7
ANOTHER EXAMPLE
32
6.100L Lecture 7
BIG IDEA
Don’t write code right
away!
33
6.100L Lecture 7
PAPER FIRST
34
6.100L Lecture 7
SIMPLE TEST CASE
2 3 4
a b 35
6.100L Lecture 7
MORE COMPLEX TEST CASE
2 3 4 5 6 7
a b 36
6.100L Lecture 7
2 3 4
SOLVE SIMILAR PROBLEM
a b
37
6.100L Lecture 7
2 3 4
CHOOSE BIG-PICTURE STRUCTURE
a b
38
6.100L Lecture 7
WRITE the LOOP 2 3 4
(for adding all numbers)
a b
39
6.100L Lecture 7
DO the SUMMING 2 3 4
(for adding all numbers)
a b
40
6.100L Lecture 7
INITIALIZE the SUM 2 3 4
(for adding all numbers)
a b
41
6.100L Lecture 7
TEST! 2 3 4
(for adding all numbers)
a b
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
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
6.100L Lecture 7
FIX for LOOP END INDEX 2 3 4
(for adding all numbers)
a b
6.100L Lecture 7
2 3 4
ADD IN THE ODD PART!
a b
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
6.100L Lecture 7
PYTHON TUTOR
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
52
6.100L Lecture 7
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
53
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
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
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
56
LAMBDA FUNCTIONS,
TUPLES and LISTS
(download slides and .py files to follow along)
6.100L Lecture 9
Ana Bell
1
FROM LAST TIME
def apply(criteria,n):
"""
* criteria: function that takes in a number and returns a bool
* n: an int
Returns how many ints from 0 to n (inclusive) match the
criteria (i.e. return True when run with criteria) """
count = 0
for i in range(n+1):
if criteria(i):
count += 1
return count
def is_even(x):
return x%2==0
print(apply(is_even,10))
6.100L Lecture 9
ANONYMOUS FUNCTIONS
lambda x: x%2 == 0
Body of lambda
parameter Note no return keyword
6.100L Lecture 9
ANONYMOUS FUNCTIONS
apply( is_even , 10 )
6.100L Lecture 9
YOU TRY IT!
What does this print?
6.100L Lecture 9
YOU TRY IT!
What does this print?
Global environment
6.100L Lecture 9
YOU TRY IT!
What does this print?
6.100L Lecture 9
YOU TRY IT!
What does this print?
6.100L Lecture 9
YOU TRY IT!
What does this print?
lambda x: x**2
environment
x 3
9
6.100L Lecture 9
YOU TRY IT!
What does this print?
lambda x: x**2
environment
x 3
10
Returns 9
6.100L Lecture 9
YOU TRY IT!
What does this print?
11
6.100L Lecture 9
YOU TRY IT!
What does this print?
12
6.100L Lecture 9
TUPLES
13
6.100L Lecture 9
A NEW DATA TYPE
14
6.100L Lecture 9
TUPLES
t = (2, "mit", 3)
t[0] evaluates to 2
(2,"mit",3) + (5,6)evaluates to a new tuple(2,"mit",3,5,6)
t[1:2] slice tuple, evaluates to ("mit",)
t[1:3] slice tuple, evaluates to ("mit",3)
len(t) evaluates to 3
max((3,5,0)) evaluates 5
t[1] = 4 gives error, can’t modify object
15
6.100L Lecture 9
INDICES AND SLICING
seq = (2,'a',4,(1,2))
index: 0 1 2 3
print(len(seq)) 4
print(seq[3]) (1,2)
print(seq[-1]) (1,2)
print(seq[3][0]) 1
print(seq[4]) error
print(seq[1]) 'a'
print(seq[-2:] (4,(1,2))
print(seq[1:4:2] ('a',(1,2))
print(seq[:-1]) (2,'a',4)
print(seq[1:3]) ('a',4)
for e in seq: 2
print(e) a
4
(1,2) 16
6.100L Lecture 9
TUPLES
17
6.100L Lecture 9
TUPLES
both = quotient_and_remainder(10,3)
18
6.100L Lecture 9
BIG IDEA
Returning
one object (a tuple)
allows you to return
multiple values (tuple elements)
19
6.100L Lecture 9
YOU TRY IT!
Write a function that meets these specs:
Hint: remember how to check if a character is in a string?
def char_counts(s):
""" s is a string of lowercase chars
Return a tuple where the first element is the
number of vowels in s and the second element
is the number of consonants in s """
20
6.100L Lecture 9
VARIABLE NUMBER of
ARGUMENTS
6.100L Lecture 9
LISTS
22
6.100L Lecture 9
LISTS
23
6.100L Lecture 9
INDICES and ORDERING
a_list = []
L = [2, 'a', 4, [1,2]]
[1,2]+[3,4] evaluates to [1,2,3,4]
len(L) evaluates to 4
L[0] evaluates to 2
L[2]+1 evaluates to 5
L[3] evaluates to [1,2], another list!
L[4] gives an error
i = 2
L[i-1] evaluates to 'a' since L[1]='a'
max([3,5,0]) evaluates 5
24
6.100L Lecture 9
ITERATING OVER a LIST
total = 0 total = 0
for i in range(len(L)): for i in L:
total += L[i] total += i
print(total) print(total)
Notice
• list elements are indexed 0 to len(L)-1
and range(n) goes from 0 to n-1
25
6.100L Lecture 9
ITERATING OVER a LIST
def list_sum(L):
total = 0 total = 0
for i in L: for i in L:
# i is 8 then 3 then 5
total += i total += i
print(total) return total
6.100L Lecture 9
LISTS SUPPORT ITERATION
27
6.100L Lecture 9
YOU TRY IT!
Write a function that meets these specs:
def sum_and_prod(L):
""" L is a list of numbers
Return a tuple where the first value is the
sum of all elements in L and the second value
is the product of all elements in L """
28
6.100L Lecture 9
SUMMARY
6.100L Lecture 9
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
30
LISTS, MUTABILITY
(download slides and .py files to follow along)
6.100L Lecture 10
Ana Bell
1
INDICES and ORDERING in LISTS
a_list = []
L = [2, 'a', 4, [1,2]]
len(L) evaluates to 4
L[0] evaluates to 2
L[3] evaluates to [1,2], another list!
[2,'a'] + [5,6] evaluates to [2,'a',5,6]
max([3,5,0]) evaluates to 5
L[1:3] evaluates to ['a', 4]
for e in L loop variable becomes each element in L
L[3] = 10 mutates L to [2,'a',4,10]
2
6.100L Lecture 10
MUTABILITY
[2,4,3]
[2,5,3]
L
3
6.100L Lecture 10
MUTABILITY
Compare
Making L by mutating an element vs.
Making t by creating a new object
L = [2, 4, 3]
L[1] = 5 L [2,5,3]
[2,4,3]
t = (2, 4, 3) t x (2,4,3)
t = (2, 5, 3) (2,5,3)
6.100L Lecture 10
OPERATION ON LISTS – append
[2,1,3]
[2,1,3,5]
L
6.100L Lecture 10
5
OPERATION ON LISTS – append
[2,1,3]
[2,1,3,5]
L
6.100L Lecture 10
6
OPERATION ON LISTS – append
[2,1,3,5,5]
[2,1,3]
L
6.100L Lecture 10
7
OPERATION ON LISTS – append
[2,1,3,5,5]
[2,1,3]
None
L
6.100L Lecture 10
8
OPERATION ON LISTS – append
L
6.100L Lecture 10
9
YOU TRY IT!
What is the value of L1, L2, L3 and L at the end?
L1 = ['re']
L2 = ['mi']
L3 = ['do']
L4 = L1 + L2
[Link](L4)
L = [Link](L3)
10
6.100L Lecture 10
BIG IDEA
Some functions mutate
the list and don’t return
anything.
We use these functions for their side effect.
11
6.100L Lecture 10
OPERATION ON LISTS: append
L = [2,1,3]
[Link](5)
6.100L Lecture 10
YOU TRY IT!
Write a function that meets these specs:
def make_ordered_list(n):
""" n is a positive int
Returns a list containing all ints in order
from 0 to n (inclusive)
"""
13
6.100L Lecture 10
YOU TRY IT!
Write a function that meets the specification.
def remove_elem(L, e):
"""
L is a list
Returns a new list with elements in the same order as L
but without any elements equal to e.
"""
L = [1,2,2,2]
print(remove_elem(L, 2)) # prints [1]
14
6.100L Lecture 10
STRINGS to LISTS
15
6.100L Lecture 10
LISTS to STRINGS
16
6.100L Lecture 10
YOU TRY IT!
Write a function that meets these specs:
def count_words(sen):
""" sen is a string representing a sentence
Returns how many words are in s (i.e. a word is a
a sequence of characters between spaces. """
17
6.100L Lecture 10
A FEW INTERESTING LIST
OPERATIONS
Add an element to end of list with [Link](element)
mutates the list
sort()
L = [4,2,7]
[Link]()
Mutates L
reverse()
L = [4,2,7]
[Link]()
Mutates L
sorted()
L = [4,2,7]
L_new = sorted(L)
Returns a sorted version of L (no mutation!)
18
6.100L Lecture 10
MUTABILITY
L=[9,6,0,3]
[Link](5)
a = sorted(L) returns a new sorted list, does not mutate L
[9,6,0,3,5]
[9,6,0,3]
19
6.100L Lecture 10
MUTABILITY
L=[9,6,0,3]
[Link](5)
a = sorted(L) returns a new sorted list, does not mutate L
[9,6,0,3,5]
L
[0,3,5,6,9]
a
20
6.100L Lecture 10
MUTABILITY
L=[9,6,0,3]
[Link](5)
a = sorted(L) returns a new sorted list, does not mutate L
None
b
[0,3,5,6,9]
[9,6,0,3,5]
L
[0,3,5,6,9]
a
21
6.100L Lecture 10
MUTABILITY
L=[9,6,0,3]
[Link](5)
a = sorted(L) returns a new sorted list, does not mutate L
None
b
[9,6,5,3,0]
[0,3,5,6,9]
L
[0,3,5,6,9]
a
22
6.100L Lecture 10
YOU TRY IT!
Write a function that meets these specs:
def sort_words(sen):
""" sen is a string representing a sentence
Returns a list containing all the words in sen but
sorted in alphabetical order. """
23
6.100L Lecture 10
BIG IDEA
Functions with side
effects mutate inputs.
You can write your own!
24
6.100L Lecture 10
LISTS SUPPORT ITERATION
def square_list(L):
for elem in L:
# ?? How to do L[index] = the square ??
# ?? elem is an element in L, not the index :(
6.100L Lecture 10
LISTS SUPPORT ITERATION
def square_list(L):
for i in range(len(L)):
L[i] = L[i]**2
Note, no return!
26
6.100L Lecture 10
TRACE the CODE with an
EXAMPLE
Example: square every element of a list, mutating original list
def square_list(L):
for i in range(len(L)):
L[i] = L[i]**2
Suppose L is [2,3,4]
i is 0: L is mutated to [4, 3, 4]
i is 1: L is mutated to [4, 9, 4]
i is 2: L is mutated to [4, 9, 16]
27
6.100L Lecture 10
TRACE the CODE with an
EXAMPLE
Example: square every element of a list, mutating original list
def square_list(L):
for i in range(len(L)):
L[i] = L[i]**2
Lin = [2,3,4]
print("before fcn call:",Lin) # prints [2,3,4]
square_list(Lin)
print("after fcn call:",Lin) # prints [4,9,16]
28
6.100L Lecture 10
BIG IDEA
Functions that mutate
the input likely…..
Iterate over len(L) not L.
Return None, so the function call does not need to be saved.
29
6.100L Lecture 10
MUTATION
30
6.100L Lecture 10
TRICKY EXAMPLES OVERVIEW
TRICKY EXAMPLE 1:
A loop iterates over indices of L and mutates L each time (adds more
elements).
TRICKY EXAMPLE 2:
A loop iterates over L’s elements directly and mutates L each time (adds
more elements).
TRICKY EXAMPLE 3:
A loop iterates over L’s elements directly but reassigns L to a new
object each time
TRICKY EXAMPLE 4 (next time):
A loop iterates over L’s elements directly and mutates L by removing
elements.
31
6.100L Lecture 10
TRICKY EXAMPLE 1: append
6.100L Lecture 10
TRICKY EXAMPLE 1: append
L = [1,2,3,4]
for i in range(len(L)):
[Link](i) [1,2,3,4,0,1,2]
[1,2,3,4,0]
[1,2,3,4]
[1,2,3,4,0,1]
[1,2,3,4,0,1,2,3]
print(L) L
(0,1,2,3)
i
1st time: L is [1, 2, 3, 4, 0]
2nd time: L is [1, 2, 3, 4, 0, 1]
3rd time: L is [1, 2, 3, 4, 0, 1, 2]
4th time: L is [1, 2, 3, 4, 0, 1, 2, 3]
33
6.100L Lecture 10
TRICKY EXAMPLE 2: append
for e in L: 1
3
0
2
L
[Link](i)
i
i += 1
print(L) 1st time: L is [1, 2, 3, 4, 0]
2nd time: L is [1, 2, 3, 4, 0, 1]
In previous example, L was accessed at
onset to create a range iterable; in this 3rd time: L is [1, 2, 3, 4, 0, 1, 2]
example, the loop is directly accessing 4th time: L is [1, 2, 3, 4, 0, 1, 2, 3]
indices into L NEVER STOPS!
34
6.100L Lecture 10
COMBINING LISTS
L1 [2,1,3]
L2 [4,5,6]
L3 [2,1,3,4,5,6]
35
6.100L Lecture 10
COMBINING LISTS
L1 [2,1,3]
[2,1,3,0,6]
L2 [4,5,6]
L3 [2,1,3,4,5,6]
36
6.100L Lecture 10
COMBINING LISTS
L1 [2,1,3]
[2,1,3,0,6]
L2 [4,5,6]
[4,5,6,[1,2],[3,4]]
L3 [2,1,3,4,5,6]
37
6.100L Lecture 10
TRICKY EXAMPLE 3: combining
6.100L Lecture 10
TRICKY EXAMPLE 3: combining
e
L = [1,2,3,4]
for e in L: [1,2,3,4]
[1,2,3,4,1,2,3,4]
L = L + L L
print(L)
39
6.100L Lecture 10
TRICKY EXAMPLE 3: combining
e
L = [1,2,3,4]
for e in L: [1,2,3,4]
[1,2,3,4,1,2,3,4]
L = L + L L
[1,2,3,4,1,2,3,4,
1,2,3,4,1,2,3,4]
print(L)
40
6.100L Lecture 10
TRICKY EXAMPLE 3: combining
e
L = [1,2,3,4]
for e in L: [1,2,3,4]
[1,2,3,4,1,2,3,4]
L = L + L L
[1,2,3,4,1,2,3,4,
1,2,3,4,1,2,3,4]
print(L)
[1,2,3,4,1,2,3,4,
1,2,3,4,1,2,3,4,
1st time: new L is [1, 2, 3, 4, 1, 2, 3, 4] 1,2,3,4,1,2,3,4,
1,2,3,4,1,2,3,4,]
2nd time: new L is [1, 2, 3, 4, 1, 2, 3, 4,
1, 2, 3, 4, 1, 2, 3, 4 ]
3rd time: new L is [1, 2, 3, 4, 1, 2, 3, 4,
1, 2, 3, 4, 1, 2, 3, 4 ,
1, 2, 3, 4, 1, 2, 3, 4,
1, 2, 3, 4, 1, 2, 3, 4] 41
6.100L Lecture 10
TRICKY EXAMPLE 3: combining
e
L = [1,2,3,4]
for e in L: [1,2,3,4]
[1,2,3,4,1,2,3,4]
L = L + L L
[1,2,3,4,1,2,3,4,
1,2,3,4,1,2,3,4]
print(L)
[1,2,3,4,1,2,3,4,
4th time: new L is [1, 2, 3, 4, 1, 2, 3, 4, 1,2,3,4,1,2,3,4,
1, 2, 3, 4, 1, 2, 3, 4 , 1,2,3,4,1,2,3,4,
1,2,3,4,1,2,3,4,]
1, 2, 3, 4, 1, 2, 3, 4,
1, 2, 3, 4, 1, 2, 3, 4 [1,2,3,4,1,2,3,4,
1,2,3,4,1,2,3,4,
1, 2, 3, 4, 1, 2, 3, 4, 1,2,3,4,1,2,3,4,
1, 2, 3, 4, 1, 2, 3, 4 , 1,2,3,4,1,2,3,4,
1,2,3,4,1,2,3,4,
1, 2, 3, 4, 1, 2, 3, 4, 1,2,3,4,1,2,3,4,
1, 2, 3, 4, 1, 2, 3, 4 ] 42
1,2,3,4,1,2,3,4,
1,2,3,4,1,2,3,4,]
6.100L Lecture 10
EMPTY OUT A LIST AND CHECKING
THAT IT’S THE SAME OBJECT
You can mutate a list to remove all its elements
This does not make a new empty list!
Use [Link]()
How to check that it’s the same object in memory?
Use the id() function
Try this in the console
>>> L = [4,5,6] >>> L = [4,5,6]
>>> id(L) >>> id(L)
>>> [Link](8) >>> [Link](8)
>>> id(L) >>> id(L)
>>> [Link]() >>> L = []
>>> id(L) >>> id(L)
43
6.100L Lecture 10
SUMMARY
44
6.100L Lecture 10
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
45
ALIASING,
CLONING
(download slides and .py files to follow along)
6.100L Lecture 11
Ana Bell
1
MAKING A COPY OF THE LIST
Loriginal [4,5,6]
Lnew [4,5,6]
6.100L Lecture 11
YOU TRY IT!
Write a function that meets the specification.
Hint. Make a copy to save the elements. The use [Link]() to
empty out the list and repopulate it with the ones you’re
keeping.
def remove_all(L, e):
"""
L is a list
Mutates L to remove all elements in L that are equal to e
Returns None
"""
L = [1,2,2,2]
remove_all(L, 2)
print(L) # prints [1]
6.100L Lecture 11
OPERATION ON LISTS: remove
6.100L Lecture 11
EXERCISE WITH REMOVE INSTEAD
OF COPY AND CLEAR
Rewrite the code to remove e as long as we still had it in the list
It works well!
6.100L Lecture 11
EXERCISE WITH REMOVE INSTEAD
OF COPY AND CLEAR
What if the code was this:
L = [1,2,2,2]
remove_all(L, 2)
print(L) # should print [1]
6.100L Lecture 11
EXERCISE WITH REMOVE INSTEAD
OF COPY AND CLEAR
L = [1,2,2,2]
remove_all(L, 2) L [1,2,2,2]
print(L) # should print [1]
6.100L Lecture 11
EXERCISE WITH REMOVE INSTEAD
OF COPY AND CLEAR
L = [1,2,2,2]
remove_all(L, 2) L [1,2,2,2]
print(L) # should print [1]
6.100L Lecture 11
EXERCISE WITH REMOVE INSTEAD
OF COPY AND CLEAR
L = [1,2,2,2]
remove_all(L, 2) L [1,2,2,2]
[1,2,2]
print(L) # should print [1]
6.100L Lecture 11
EXERCISE WITH REMOVE INSTEAD
OF COPY AND CLEAR
L = [1,2,2,2]
remove_all(L, 2) L [1,2,2]
print(L) # should print [1]
10
6.100L Lecture 11
EXERCISE WITH REMOVE INSTEAD
OF COPY AND CLEAR
It’s not correct! We removed items as we iterated over the list!
L = [1,2,2,2]
remove_all(L, 2) L [1,2]
[1,2,2]
print(L) # should print [1]
11
6.100L Lecture 11
TRICKY EXAMPLES OVERVIEW
TRICKY EXAMPLE 1:
A loop iterates over indices of L and mutates L each time (adds more
elements).
TRICKY EXAMPLE 2:
A loop iterates over L’s elements directly and mutates L each time (adds
more elements).
TRICKY EXAMPLE 3:
A loop iterates over L’s elements directly but reassigns L to a new
object each time
TRICKY EXAMPLE 4:
A loop iterates over L’s elements directly and mutates L by removing
elements.
12
6.100L Lecture 11
TRICKY EXAMPLE 4
PYTHON TUTOR LINK to see step-by-step
6.100L Lecture 11
MUTATION AND ITERATION WITHOUT CLONE
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2)
L1 [10,20,30,40]
L2 [10,20,50,60]
14
6.100L Lecture 11
MUTATION AND ITERATION WITHOUT CLONE
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2)
L1 [20,30,40]
L2 [10,20,50,60]
15
6.100L Lecture 11
MUTATION AND ITERATION WITHOUT CLONE
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2)
L1 [20,30,40]
L2 [10,20,50,60]
16
6.100L Lecture 11
MUTATION AND ITERATION WITHOUT CLONE
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2)
L1 [20,30,40]
L2 [10,20,50,60]
17
6.100L Lecture 11
MUTATION AND ITERATION WITH CLONE
L1_copy = L1[:]
6.100L Lecture 11
def remove_dups(L1, L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
[Link](e)
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2)
L1_copy [10,20,30,40]
L1 [10,20,30,40]
L2 [10,20,50,60]
19
6.100L Lecture 11
def remove_dups(L1, L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
[Link](e)
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2)
L1_copy [10,20,30,40]
L1 [20,30,40]
L2 [10,20,50,60]
20
6.100L Lecture 11
def remove_dups(L1, L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
[Link](e)
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2)
L1_copy [10,20,30,40]
L1 [20,30,40]
L2 [10,20,50,60]
21
6.100L Lecture 11
def remove_dups(L1, L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
[Link](e)
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2)
L1_copy [10,20,30,40]
L1 [30,40]
L2 [10,20,50,60]
22
6.100L Lecture 11
def remove_dups(L1, L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
[Link](e)
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2)
L1_copy [10,20,30,40]
L1 [30,40]
L2 [10,20,50,60]
23
6.100L Lecture 11
def remove_dups(L1, L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
[Link](e)
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2)
L1_copy [10,20,30,40]
L1 [30,40]
L2 [10,20,50,60]
24
6.100L Lecture 11
ALIASING
… all the aliases refer to the old attribute and all the new ones
The Hub small tech-savvy snowy
25
6.100L Lecture 11
MUTATION AND ITERATION WITH ALIAS
L1_copy = L1
6.100L Lecture 11
def remove_dups(L1, L2):
L1_copy = L1
for e in L1_copy:
if e in L2:
[Link](e)
e
L1 = [10, 20, 30, 40]
L2 = [10, 20, 50, 60]
remove_dups(L1, L2) L1_copy
L1 [20,30,40]
[10,20,30,40]
L2 [10,20,50,60]
27
6.100L Lecture 11
BIG IDEA
When you pass a list as a
parameter to a function,
you are making an alias.
The actual parameter (from the function call) is an alias for
the formal parameter (from the function definition).
28
6.100L Lecture 11
def remove_dups(L1, L2):
L1_copy = L1
for e in L1_copy:
if e in L2:
[Link](e)
e
La = [10, 20, 30, 40]
Lb = [10, 20, 50, 60]
remove_dups(La, Lb) L1_copy
print(La) La [20,30,40]
[10,20,30,40]
L1
Lb [10,20,50,60]
L2
29
6.100L Lecture 11
ALIASES,
SHALLOW COPIES, AND
DEEP COPIES WITH
MUTABLE ELEMENTS
30
6.100L Lecture 11
CONTROL COPYING
new_list[2][1] = 6
print("New list:", new_list) New list: [[1,2],[3,4],[5,6]]
print("Old list:", old_list) Old list: [[1,2],[3,4],[5,6]]
So mutating one object changes the other
[ , , ]
new_list
31
6.100L Lecture 11
CONTROL COPYING
6.100L Lecture 11
old_list = [[1,2],[3,4],[5,6]]
new_list = [Link](old_list)
[ , , ]
old_list
[1,2] [3,4] [5,6]
new_list 6.0001 LECTURE 5
[ , , ]
33
6.100L Lecture 11
CONTROL COPYING
old_list.append([7,8])
print("New list:", new_list)
print("Old list:", old_list)
34
6.100L Lecture 11
old_list = [[1,2],[3,4],[5,6]]
new_list = [Link](old_list)
old_list.append([7,8])
print("New list:", new_list)
New list: [[1,2],[3,4],[5,6]]
print("Old list:", old_list)
Old list: [[1,2],[3,4],[5,6],[7,8]]
[[ ,, ,, ], ]
old_list
[1,2] [3,4] [5,6] [7,8]
new_list 6.0001 LECTURE 5
35
[ , , ]
6.100L Lecture 11
CONTROL COPYING
old_list.append([7,8])
old_list[1][1] = 9
print("New list:", new_list)
print("Old list:", old_list)
36
6.100L Lecture 11
old_list = [[1,2],[3,4],[5,6]]
new_list = [Link](old_list)
old_list.append([7,8])
old_list[1][1] = 9
print("New list:", new_list) New list: [[1,2],[3,9],[5,6]]
print("Old list:", old_list) Old list: [[1,2],[3,9],[5,6],[7,8]]
[[ ,, ,, ], ]
old_list
[1,2] [3,4]
[3,9] [5,6] [7,8]
new_list 6.0001 LECTURE 5
[
37
, , ]
6.100L Lecture 11
CONTROL COPYING
old_list.append([7,8])
old_list[1][1] = 9
print("New list:", new_list)
print("Old list:", old_list)
38
6.100L Lecture 11
old_list = [[1,2],[3,4],[5,6]]
new_list = [Link](old_list)
old_list.append([7,8])
old_list[1][1] = 9
print("New list:", new_list) New list: [[1,2],[3,4],[5,6]]
print("Old list:", old_list) Old list: [[1,2],[3,9],[5,6],[7,8]]
[ , , ]
, ]
[39 , , ]
6.100L Lecture 11
LISTS in MEMORY
Separate the idea of the object vs. the name we give an object
A list is an object in memory
Variable name points to object
Lists are mutable and behave differently than immutable types
Using equal sign between mutable objects creates aliases
Both variables point to the same object in memory
Any variable pointing to that object is affected by mutation of object,
even if mutation is by referencing another name
If you want a copy, you explicitly tell Python to make a copy
Key phrase to keep in mind when working with lists is side
effects, especially when dealing with aliases – two names
pointing to the same structure in memory
Python Tutor is your best friend to help sort this out!
[Link] 40
6.100L Lecture 11
WHY LISTS and TUPLES?
41
6.100L Lecture 11
AT HOME TRACING
EXAMPLES SHOWCASING
ALIASING AND CLONING
42
6.100L Lecture 11
ALIASES
43
6.100L Lecture 11
ALIASES
44
6.100L Lecture 11
CLONING A LIST
45
6.100L Lecture 11
CLONING A LIST
46
6.100L Lecture 11
CLONING A LIST
47
6.100L Lecture 11
LISTS OF LISTS
OF LISTS OF….
Can have nested lists
Side effects still
possible after mutation
48
6.100L Lecture 11
LISTS OF LISTS
OF LISTS OF….
Can have nested lists
Side effects still
possible after mutation
49
6.100L Lecture 11
LISTS OF LISTS
OF LISTS OF….
Can have nested lists
Side effects still
possible after mutation
50
6.100L Lecture 11
LISTS OF LISTS
OF LISTS OF….
Can have nested lists
Side effects still
possible after mutation
51
6.100L Lecture 11
LISTS OF LISTS
OF LISTS OF….
Can have nested lists
Side effects still
possible after mutation
52
6.100L Lecture 11
LISTS OF LISTS
OF LISTS OF….
Can have nested lists
Side effects still
possible after mutation
53
6.100L Lecture 11
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
54
LIST COMPREHENSION,
FUNCTIONS AS OBJECTS,
TESTING, DEBUGGING
(download slides and .py files to follow along)
6.100L Lecture 12
Ana Bell
1
LIST COMPREHENSIONS
6.100L Lecture 12
LIST COMPREHENSIONS
6.100L Lecture 12
LIST COMPREHENSIONS
def f(L):
Lnew = []
for e in L: Lnew = [e**2 for e in L]
[Link](e**2)
return Lnew
6.100L Lecture 12
LIST COMPREHENSIONS
def f(L):
Lnew = []
for e in L: Lnew = [e**2 for e in L]
[Link](e**2)
return Lnew
def f(L):
Lnew = []
for e in L:
if e%2==0:
[Link](e**2)
return Lnew
5
6.100L Lecture 12
LIST COMPREHENSIONS
def f(L):
Lnew = []
for e in L: Lnew = [e**2 for e in L]
[Link](e**2)
return Lnew
def f(L):
Lnew = []
for e in L:
if e%2==0:
[Link](e**2) Lnew = [e**2 for e in L if e%2==0]
return Lnew
6
6.100L Lecture 12
LIST COMPREHENSIONS
def f(L):
Lnew = []
for e in L: Lnew = [e**2 for e in L]
[Link](e**2)
return Lnew
def f(L):
Lnew = []
for e in L:
if e%2==0:
[Link](e**2) Lnew = [e**2 for e in L if e%2==0]
return Lnew
7
6.100L Lecture 12
LIST COMPREHENSIONS
def f(L):
Lnew = []
for e in L: Lnew = [e**2 for e in L]
[Link](e**2)
return Lnew
def f(L):
Lnew = []
for e in L:
if e%2==0:
[Link](e**2) Lnew = [e**2 for e in L if e%2==0]
return Lnew
8
6.100L Lecture 12
LIST COMPREHENSIONS
6.100L Lecture 12
YOU TRY IT!
What is the value returned by this expression?
Step1: what are all values in the sequence
Step2: which subset of values does the condition filter out?
Step3: apply the function to those values
10
6.100L Lecture 12
FUNCTIONS: DEFAULT
PARAMETERS
11
6.100L Lecture 12
SQUARE ROOT with BISECTION
def bisection_root(x):
epsilon = 0.01
low = 0
high = x
guess = (high + low)/2.0
while abs(guess**2 - x) >= epsilon:
if guess**2 < x:
low = guess
else:
high = guess
guess = (high + low)/2.0
return guess
print(bisection_root(123))
12
6.100L Lecture 12
ANOTHER PARAMETER
13
6.100L Lecture 12
epsilon as a PARAMETER
print(bisection_root(123, 0.01))
14
6.100L Lecture 12
KEYWORD PARAMETERS &
DEFAULT VALUES
def bisection_root(x, epsilon)can be improved
We added epsilon as an argument to the function
Most of the time we want some standard value, 0.01
Sometimes, we may want to use some other value
Use a keyword parameter aka a default parameter
15
6.100L Lecture 12
Epsilon as a KEYWORD
PARAMETER
def bisection_root(x, epsilon=0.01):
low = 0
high = x
guess = (high + low)/2.0
while abs(guess**2 - x) >= epsilon:
if guess**2 < x:
low = guess
else:
high = guess
guess = (high + low)/2.0
return guess
print(bisection_root(123))
print(bisection_root(123, 0.5))
16
6.100L Lecture 12
RULES for KEYWORD PARAMETERS
17
6.100L Lecture 12
FUNCTIONS RETURNING
FUNCTIONS
18
6.100L Lecture 12
OBJECTS IN A PROGRAM
function
my_func object
named
is_even is_even
pi = 22/7
a False
my_func = is_even
b True
a = is_even(3)
b = my_func(4)
19
6.100L Lecture 12
FUNCTIONS CAN RETURN
FUNCTIONS
def make_prod(a):
def g(b):
return a*b
return g
20
6.100L Lecture 12
SCOPE DETAILS FOR WAY 1
def make_prod(a):
def g(b):
return a*b
return g
val = make_prod(2)(3)
print(val)
21
6.100L Lecture 12
SCOPE DETAILS FOR WAY 1
val = make_prod(2)(3)
print(val)
22
6.100L Lecture 12
SCOPE DETAILS FOR WAY 1 NOTE: definition
of g is done
within scope of
make_prod, so
binding of g is
def make_prod(a): Global scope make_prod within that
scope frame/scope
def g(b):
make_prod Some Since g is bound
return a*b a 2 in this frame,
code
cannot access it
return g by evaluation in
Some global frame
g
code g can only be
val = make_prod(2)(3) accessed within
call to
print(val) make_prod, and
each call will
create a new,
internal g
23
6.100L Lecture 12
SCOPE DETAILS FOR WAY 1
25
6.100L Lecture 12
SCOPE DETAILS FOR WAY 1
def make_prod(a):
def g(b):
return a*b
return g
doubler = make_prod(2)
val = doubler(3)
print(val)
27
6.100L Lecture 12
SCOPE DETAILS FOR WAY 2
28
6.100L Lecture 12
SCOPE DETAILS FOR WAY 2
29
6.100L Lecture 12
SCOPE DETAILS FOR WAY 2
Returns value
30
6.100L Lecture 12
WHY BOTHER RETURNING
FUNCTIONS?
Code can be rewritten without returning function objects
Good software design
Embracing ideas of decomposition, abstraction
Another tool to structure code
Interrupting execution
Example of control flow
A way to achieve partial execution and use result somewhere else
before finishing the full evaluation
31
6.100L Lecture 12
TESTING and
DEBUGGING
32
6.100L Lecture 12
DEFENSIVE PROGRAMMING
• Write specifications for functions
• Modularize programs
• Check conditions on inputs/outputs (assertions)
TESTING/VALIDATION DEBUGGING
• Compare input/output • Study events leading up
pairs to specification to an error
• “It’s not working!” • “Why is it not working?”
• “How can I break my • “How can I fix my
program?” program?”
33
6.100L Lecture 12
SET YOURSELF UP FOR EASY
TESTING AND DEBUGGING
34
6.100L Lecture 12
WHEN ARE YOU READY TO TEST?
35
6.100L Lecture 12
CLASSES OF TESTS
Unit testing
• Validate each piece of program
• Testing each function separately
Regression testing
• Add test for bugs as you find them
• Catch reintroduced errors that were previously
fixed
Integration testing
• Does overall program work?
• Tend to rush to do this
36
6.100L Lecture 12
TESTING APPROACHES
6.100L Lecture 12
BLACK BOX TESTING
38
6.100L Lecture 12
BLACK BOX TESTING
CASE x eps
boundary 0 0.0001
perfect square 25 0.0001
less than 1 0.05 0.0001
irrational square root 2 0.0001
extremes 2 1.0/2.0**64.0
extremes 1.0/2.0**64.0 1.0/2.0**64.0
extremes 2.0**64.0 1.0/2.0**64.0
extremes 1.0/2.0**64.0 2.0**64.0
extremes 2.0**64.0 39 2.0**64.0
6.100L Lecture 12
GLASS BOX TESTING
40
6.100L Lecture 12
GLASS BOX TESTING
def abs(x):
""" Assumes x is an int
Returns x if x>=0 and –x otherwise """
if x < -1:
return –x
else:
return x
Aa path-complete test suite could miss a bug
Path-complete test suite: 2 and -2
But abs(-1) incorrectly returns -1
Should still test boundary cases
41
6.100L Lecture 12
DEBUGGING
Once you have discovered that your code does not run
properly, you want to:
Isolate the bug(s)
Eradicate the bug(s)
Retest until code runs correctly for all cases
Steep learning curve
Goal is to have a bug-free program
Tools
• Built in to IDLE and Anaconda
• Python Tutor
• print statement
• Use your brain, be systematic in your hunt
42
6.100L Lecture 12
ERROR MESSAGES – EASY
6.100L Lecture 12
LOGIC ERRORS - HARD
44
6.100L Lecture 12
DEBUGGING STEPS
45
6.100L Lecture 12
PRINT STATEMENTS
46
6.100L Lecture 12
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
47
EXCEPTIONS,
ASSERTIONS
(download slides and .py files to follow along)
6.100L Lecture 13
Ana Bell
1
EXCEPTIONS
2
UNEXPECTED
CONDITIONS
6.100L Lecture 13
HANDLING EXCEPTIONS
6.100L Lecture 13
EXAMPLE with CODE YOU MIGHT
HAVE ALREADY SEEN
A function that sums digits in a string
CODE YOU’VE SEEN CODE WITH EXCEPTIONS
def sum_digits(s): def sum_digits(s):
""" s is a non-empty string """ s is a non-empty string
containing digits. containing digits.
Returns sum of all chars that Returns sum of all chars that
are digits """ are digits """
total = 0 total = 0
for char in s: for char in s:
if char in '0123456789': try:
val = int(char) val = int(char)
total += val total += val
return total except:
print("can't convert", char)
return total
5
6.100L Lecture 13
USER INPUT CAN LEAD TO
EXCEPTIONS
6.100L Lecture 13
HANDLING SPECIFIC EXCEPTIONS
6.100L Lecture 13
OTHER BLOCKS ASSOCIATED WITH
A TRY BLOCK
else:
• Body of this is executed when execution of associated try body
completes with no exceptions
finally:
• Body of this is always executed after try, else and except clauses,
even if they raised another error or executed a break, continue or
return
• Useful for clean-up code that should be run no matter what else
happened (e.g. close a file)
Nice to know these exist, but we don’t really use these in this
class
6.100L Lecture 13
WHAT TO DO WITH EXCEPTIONS?
6.100L Lecture 13
EXAMPLE with SOMETHING
YOU’VE ALREADY SEEN
A function that sums digits in a string
Execution stopping means a bad result is not propagated
def sum_digits(s):
""" s is a non-empty string containing digits.
Returns sum of all chars that are digits """
total = 0
for char in s:
try:
val = int(char)
total += val
except:
raise ValueError("string contained a character")
return total
10
6.100L Lecture 13
YOU TRY IT!
def pairwise_div(Lnum, Ldenom):
""" Lnum and Ldenom are non-empty lists of equal lengths containing numbers
# For example:
L1 = [4,5,6]
L2 = [1,2,3]
# print(pairwise_div(L1, L2)) # prints [4.0,2.5,2.0]
L1 = [4,5,6]
L2 = [1,0,3]
# print(pairwise_div(L1, L2)) # raises a ValueError
11
6.100L Lecture 13
ASSERTIONS
12
6.100L Lecture 13
ASSERTIONS: DEFENSIVE
PROGRAMMING TOOL
Want to be sure that assumptions on state of computation are as
expected
Use an assert statement to raise an AssertionError
exception if assumptions not met
assert <statement that should be true>, "message if not true"
An example of good defensive programming
Assertions don’t allow a programmer to control response to unexpected
conditions
Ensure that execution halts whenever an expected condition is not met
Typically used to check inputs to functions, but can be used anywhere
Can be used to check outputs of a function to avoid propagating bad
values
Can make it easier to locate a source of a bug
13
6.100L Lecture 13
EXAMPLE with SOMETHING
YOU’VE ALREADY SEEN
A function that sums digits in a NON-EMPTY string
Execution stopping means a bad result is not propagated
def sum_digits(s):
""" s is a non-empty string containing digits.
Returns sum of all chars that are digits """
assert len(s) != 0, "s is empty"
total = 0
for char in s:
try:
val = int(char)
total += val
except:
raise ValueError("string contained a character")
14
6.100L Lecture 13
YOU TRY IT!
def pairwise_div(Lnum, Ldenom):
""" Lnum and Ldenom are non-empty lists of equal lengths
containing numbers
Returns a new list whose elements are the pairwise
division of an element in Lnum by an element in Ldenom.
Raise a ValueError if Ldenom contains 0. """
# add an assert line here
15
6.100L Lecture 13
ANOTHER EXAMPLE
16
6.100L Lecture 13
LONGER EXAMPLE OF
EXCEPTIONS and ASSERTIONS
17
6.100L Lecture 13
EXAMPLE [[['peter', 'parker'], [80.0, 70.0, 85.0]],
CODE [['bruce', 'wayne'], [100.0, 80.0, 74.0]]]
def get_stats(class_list):
new_stats = []
for stu in class_list:
new_stats.append([stu[0], stu[1], avg(stu[1])])
return new_stats
def avg(grades):
return sum(grades)/len(grades)
18
6.100L Lecture 13
ERROR IF NO GRADE FOR A
STUDENT
19
6.100L Lecture 13
OPTION 1: FLAG THE ERROR BY
PRINTING A MESSAGE
6.100L Lecture 13
OPTION 2: CHANGE THE POLICY
6.100L Lecture 13
OPTION 3: HALT EXECUTION IF
ASSERT IS NOT MET
def avg(grades):
assert len(grades) != 0, 'no grades data'
return sum(grades)/len(grades)
22
6.100L Lecture 13
ASSERTIONS vs. EXCEPTIONS
6.100L Lecture 13
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
24
DICTIONARIES
(download slides and .py files to follow along)
6.100L Lecture 14
Ana Bell
1
HOW TO STORE
STUDENT INFO
Suppose we want to store and use grade information for
a set of students
Could store using separate lists for each kind of
information
names = ['Ana', 'John', 'Matt', 'Katy']
grades = ['A+' , 'B' , 'A' , 'A' ]
microquizzes = ...
psets = ...
Info stored across lists at same index, each index refers to
information for a different person
Indirectly access information by finding location in lists
corresponding to a person, then extract
2
6.100L Lecture 14
HOW TO ACCESS
STUDENT INFO
def get_grade(student, name_list, grade_list):
i = name_list.index(student)
grade = grade_list[i]
return (student, grade)
6.100L Lecture 14
HOW TO STORE AND
ACCESS STUDENT INFO
Alternative might be to use a list of lists
eric = ['eric', ['ps', [8, 4, 5]], ['mq', [6, 7]]]
ana = ['ana', ['ps', [10, 10, 10]], ['mq', [9, 10]]]
john = ['john', ['ps', [7, 6, 5]], ['mq', [8, 5]]]
6.100L Lecture 14
A BETTER AND CLEANER WAY –
A DICTIONARY
Nice to use one data structure, no separate lists
Nice to index item of interest directly
A Python dictionary has entries that map a key:value
A list A dictionary
0 Elem 1 Key 1 Val 1
… … … …
6.100L Lecture 14
BIG IDEA
Dict value refers to the
value associated with a
key.
This terminology is may sometimes be confused with the
regular value of some variable.
6.100L Lecture 14
A PYTHON DICTIONARY
my_dict = {}
d = {4:16}
grades = {'Ana':'B', 'Matt':'A', 'John':'B', 'Katy':'A'}
6.100L Lecture 14
DICTIONARY LOOKUP
6.100L Lecture 14
YOU TRY IT!
Write a function according to this spec
def find_grades(grades, students):
""" grades is a dict mapping student names (str) to grades (str)
students is a list of student names
Returns a list containing the grades for students (in same order) """
# for example
6.100L Lecture 14
BIG IDEA
Getting a dict value is
just a matter of indexing
with a key.
No. Need. To. Loop
10
6.100L Lecture 14
'Ana' 'B'
DICTIONARY 'Matt' 'A'
OPERATIONS 'John' 'B'
'Katy' 'A'
'Grace' 'A'
'C'
Add an entry
grades['Grace'] = 'A'
Change entry
grades['Grace'] = 'C'
Delete entry
del(grades['Ana'])
11
6.100L Lecture 14
'Ana' 'B'
DICTIONARY 'Matt' 'A'
OPERATIONS 'John' 'B'
'Katy' 'A'
12
6.100L Lecture 14
YOU TRY IT!
Write a function according to these specs
def find_in_L(Ld, k):
""" Ld is a list of dicts
k is an int
Returns True if k is a key in any dicts of Ld and False otherwise """
# for example
d1 = {1:2, 3:4, 5:6}
d2 = {2:4, 4:6}
d3 = {1:1, 3:9, 4:16, 5:25}
13
6.100L Lecture 14
'Ana' 'B'
DICTIONARY 'Matt' 'A'
OPERATIONS
'John' 'B'
'Katy' 'A'
Can iterate over dictionaries but
assume there is no guaranteed order
grades = {'Ana':'B', 'Matt':'A', 'John':'B', 'Katy':'A'}
14
6.100L Lecture 14
DICTIONARY OPERATIONS 'Ana' 'B'
'Katy' 'A'
Can iterate over dictionaries but
assume there is no guaranteed order
grades = {'Ana':'B', 'Matt':'A', 'John':'B', 'Katy':'A'}
list([Link]())
returns [('Ana', 'B'), ('Matt', 'A'), ('John', 'B'), ('Katy', 'A')]
6.100L Lecture 14
YOU TRY IT!
Write a function that meets this spec
def count_matches(d):
""" d is a dict
Returns how many entries in d have the key equal to its value """
# for example
d = {1:2, 3:4, 5:6}
print(count_matches(d)) # prints 0
d = {1:2, 'a':'a', 5:5}
print(count_matches(d)) # prints 2
16
6.100L Lecture 14
DICTIONARY KEYS & VALUES
6.100L Lecture 14
WHY IMMUTABLE/HASHABLE
KEYS?
A dictionary is stored in memory in a special way
Next slides show an example
18
6.100L Lecture 14
Hash function:
1) Sum the letters Memory block (like a list)
2) Take mod 16 (to fit in a memory
block with 16 entries) 0 Ana: C
1
1 + 14 + 1 = 16
16%16 = 0 2
3
Ana C 4
Eric: A
5 + 18 + 9 + 3 = 35
35%16 = 3
5 [K,a,t,e]: B
6
Eric A 7
10 + 15 + 8 + 14 = 47 8
47%16 = 15
9
John B 10
11
12
13
11 + 1 + 20 + 5 = 37 14
37%16 = 5 15 John: B
[K, a, t, e] B 19
6.100L Lecture 14
Hash function:
1) Sum the letters Memory block (like a list)
2) Take mod 16 (to fit in a memory
block with 16 entries) 0 Ana: C
1
Kate changes her name to Cate. Same 2
person, different name. Look up her 3 Eric: A
grade? 4
5 [K,a,t,e]: B
6
7
8
9
10
11
12
13 ??? Not here!
3 + 1 + 20 + 5 = 29 14
29%16 = 13 15 John: B
[C, a, t, e] 20
6.100L Lecture 14
A PYTHON DICTIONARY for
STUDENT GRADES
21
6.100L Lecture 14
A PYTHON DICTIONARY for
STUDENT GRADES
22
6.100L Lecture 14
A PYTHON DICTIONARY for
STUDENT GRADES
23
6.100L Lecture 14
A PYTHON DICTIONARY for
STUDENT GRADES
6.100L Lecture 14
YOU TRY IT!
my_d ={'Ana':{'mq':[10], 'ps':[10,10]},
'Bob':{'ps':[7,8], 'mq':[8]},
'Eric':{'mq':[3], 'ps':[0]} }
Given the dict my_d, and the outline of a function to compute an average, which line should
be inserted where indicated so that get_average(my_d, 'mq') computes average
for all 'mq' entries? i.e. find average of all mq scores for all students.
6.100L Lecture 14
list vs dict
26
6.100L Lecture 14
EXAMPLE: FIND MOST COMMON
WORDS IN A SONG’S LYRICS
6.100L Lecture 14
CREATING A DICTIONARY
Python Tutor LINK
song = "RAH RAH AH AH AH ROM MAH RO MAH MAH"
def generate_word_dict(song):
song_words = [Link]()
words_list = song_words.split()
word_dict = {}
for w in words_list:
if w in word_dict:
word_dict[w] += 1
else:
word_dict[w] = 1
return word_dict
28
6.100L Lecture 14
USING THE DICTIONARY
Python Tutor LINK
word_dict = {'rah':2, 'ah':3, 'rom':1, 'mah':3, 'ro':1}
def find_frequent_word(word_dict):
words = []
highest = max(word_dict.values())
for k,v in word_dict.items():
if v == highest:
[Link](k)
return (words, highest)
29
6.100L Lecture 14
FIND WORDS WITH FREQUENCY
GREATER THAN x=1
Repeat the next few steps as long as the highest frequency is
greater than x
Find highest frequency
30
6.100L Lecture 14
FIND WORDS WITH FREQUENCY
GREATER THAN x=1
Use function find_frequent_word to get words with the
biggest frequency
31
6.100L Lecture 14
FIND WORDS WITH FREQUENCY
GREATER THAN x=1
Remove the entries corresponding to these words from
dictionary by mutation
freq_list = [(['ah','mah'],3)]
32
6.100L Lecture 14
FIND WORDS WITH FREQUENCY
GREATER THAN x=1
Find highest frequency in the mutated dict
freq_list = [(['ah','mah'],3)]
33
6.100L Lecture 14
FIND WORDS WITH FREQUENCY
GREATER THAN x=1
Use function find_frequent_word to get words with that
frequency
freq_list = [(['ah','mah'],3)]
34
6.100L Lecture 14
FIND WORDS WITH FREQUENCY
GREATER THAN x=1
Remove the entries corresponding to these words from
dictionary by mutation
35
6.100L Lecture 14
FIND WORDS WITH FREQUENCY
GREATER THAN x=1
The highest frequency is now smaller than x=2, so stop
36
6.100L Lecture 14
LEVERAGING DICT PROPERTIES
Python Tutor LINK
word_freq_tuple = find_frequent_word(word_dict)
freq_list.append(word_freq_tuple)
for word in word_freq_tuple[0]:
del(word_dict[word])
return freq_list
37
6.100L Lecture 14
SOME OBSERVATIONS
6.100L Lecture 14
SUMMARY
39
6.100L Lecture 14
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
40
PYTHON CLASSES
(download slides and .py files to follow along)
6.100L Lecture 17
Ana Bell
1
OBJECTS
6.100L Lecture 17
OBJECT ORIENTED
PROGRAMMING (OOP)
6.100L Lecture 17
WHAT ARE OBJECTS?
6.100L Lecture 17
EXAMPLE:
[1,2,3,4] has type list
6.100L Lecture 17
REAL-LIFE EXAMPLES
6.100L Lecture 17
ADVANTAGES OF OOP
6.100L Lecture 17
BIG IDEA
You write the class so you
make the design decisions.
You decide what data represents the class.
You decide what operations a user can do with the class.
6.100L Lecture 17
Implementing the class Using the class
6.100L Lecture 17
A PARALLEL with FUNCTIONS
10
6.100L Lecture 17
COORDINATE TYPE
DESIGN DECISIONS
Can create instances of a Decide what data elements
Coordinate object constitute an object
• In a 2D plane
• A coordinate is defined by
(3 , 4) an x and y value
11
6.100L Lecture 17
Implementing the class Using the class
class Coordinate(object):
#define attributes here
6.100L Lecture 17
WHAT ARE ATTRIBUTES?
13
6.100L Lecture 17
Implementing the class Using the class
6.100L Lecture 17
Image © source unknown. All rights
reserved. This content is excluded from
our Creative Commons license. For more
WHAT is self?
information, see [Link]
help/faq-fair-use/
ROOM EXAMPLE
Think of the class definition as a Now when you create ONE instance
blueprint with placeholders for (name it living_room), self becomes
actual items this actual object
self has a chair living_room has a blue chair
self has a coffee table living_room has a black table
self has a sofa living_room has a white sofa
Can make many instances using
the same blueprint
15
6.100L Lecture 17
BIG IDEA
When defining a class,
we don’t have an actual
tangible object here.
It’s only a definition.
16
6.100L Lecture 17
Implementing the class Using the class
6.100L Lecture 17
VISUALIZING INSTANCES
18
6.100L Lecture 17
VISUALIZING INSTANCES:
in memory
Make another instance using
a variable
a = 0 Type: Coordinate
c x: 3
orig = Coordinate(a,a) y: 4
orig.x a 0
19
6.100L Lecture 17
VISUALIZING INSTANCES:
draw it
class Coordinate(object):
def __init__(self, xval, yval):
self.x = xval
self.y = yval
(3 , 4)
c
c = Coordinate(3,4)
origin = Coordinate(0,0)
print(c.x)
print(origin.x)
(0 , 0)
origin
20
6.100L Lecture 17
WHAT IS A METHOD?
Procedural attribute
Think of it like a function that works only with this class
Python always passes the object as the first argument
Convention is to use self as the name of the first argument of all
methods
21
6.100L Lecture 17
Implementing the class Using the class
DEFINE A METHOD
FOR THE Coordinate CLASS
class Coordinate(object):
def __init__(self, xval, yval):
self.x = xval
self.y = yval
def distance(self, other):
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
Other than self and dot notation, methods behave just
like functions (take params, do operations, return)
22
6.100L Lecture 17
HOW TO CALL A METHOD?
Familiar?
my_list.append(4)
my_list.sort()
23
6.100L Lecture 17
Implementing the class Using the class
6.100L Lecture 17
VISUALIZING INVOCATION
25
6.100L Lecture 17
VISUALIZING INVOCATION
6.100L Lecture 17
Implementing the class Using the class
27
6.100L Lecture 17
BIG IDEA
The . operator accesses
either data attributes or
methods.
Data attributes are defined with [Link]
Methods are functions defined inside the class with self as the first parameter.
28
6.100L Lecture 17
THE POWER OF OOP
29
6.100L Lecture 17
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
30
MORE PYTHON CLASS
METHODS
(download slides and .py files to follow along)
6.100L Lecture 18
Ana Bell
1
IMPLEMENTING USING
THE CLASS vs THE CLASS
6.100L Lecture 18
RECALL THE COORDINATE CLASS
class Coordinate(object):
""" A coordinate made up of an x and y value """
def __init__(self, x, y):
""" Sets the x and y values """
self.x = x
self.y = y
def distance(self, other):
""" Returns euclidean dist between two Coord obj """
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
6.100L Lecture 18
ADDING METHODS TO THE
COORDINATE CLASS
Methods are functions that only work with objects of this type
class Coordinate(object):
""" A coordinate made up of an x and y value """
def __init__(self, x, y):
""" Sets the x and y values """
self.x = x
self.y = y
def distance(self, other):
""" Returns euclidean dist between two Coord obj """
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
def to_origin(self):
""" always sets self.x and self.y to 0,0 """
self.x = 0
self.y = 0
4
6.100L Lecture 18
MAKING COORDINATE INSTANCES
c = Coordinate(3,4)
origin = Coordinate(0,0)
c.to_origin()
print(c.x, c.y)
5
6.100L Lecture 18
CLASS DEFINITION INSTANCE
OF AN OBJECT TYPE vs OF A CLASS
6.100L Lecture 18
USING CLASSES TO BUILD OTHER
CLASSES
Example: use Coordinates to build Circles
Our implementation will use 2 data attributes
Coordinate object representing the center
int object representing the radius
radius
Center
coordinate
6.100L Lecture 18
CIRCLE CLASS:
DEFINITION and INSTANCES
class Circle(object):
def __init__(self, center, radius):
[Link] = center
[Link] = radius
center = Coordinate(2, 2)
my_circle = Circle(center, 2)
6.100L Lecture 18
YOU TRY IT!
Add code to the init method to check that the type of center is
a Coordinate obj and the type of radius is an int. If either are
not these types, raise a ValueError.
6.100L Lecture 18
CIRCLE CLASS:
DEFINITION and INSTANCES
class Circle(object):
def __init__(self, center, radius):
[Link] = center
[Link] = radius
def is_inside(self, point):
""" Returns True if point is in self, False otherwise """
return [Link]([Link]) < [Link]
center = Coordinate(2, 2)
my_circle = Circle(center, 2)
p = Coordinate(1,1)
print(my_circle.is_inside(p))
10
6.100L Lecture 18
YOU TRY IT!
Are these two methods in the Circle class functionally equivalent?
class Circle(object):
def __init__(self, center, radius):
[Link] = center
[Link] = radius
11
6.100L Lecture 18
EXAMPLE:
FRACTIONS
12
6.100L Lecture 18
NEED TO CREATE INSTANCES
class SimpleFraction(object):
def __init__(self, n, d):
[Link] = n
[Link] = d
13
6.100L Lecture 18
MULTIPLY FRACTIONS
class SimpleFraction(object):
def __init__(self, n, d):
[Link] = n
[Link] = d
def times(self, oth):
top = [Link]*[Link]
bottom = [Link]*[Link]
return top/bottom
14
6.100L Lecture 18
ADD FRACTIONS
class SimpleFraction(object):
def __init__(self, n, d):
[Link] = n
[Link] = d
………
def plus(self, oth):
top = [Link]*[Link] + [Link]*[Link]
bottom = [Link]*[Link]
return top/bottom
15
6.100L Lecture 18
LET’S TRY IT OUT
f1 = SimpleFraction(3, 4)
f2 = SimpleFraction(1, 4)
print([Link]) 3
print([Link]) 4
print([Link](f2)) 1.0
print([Link](f2)) 0.1875
16
6.100L Lecture 18
YOU TRY IT!
Add two methods to invert fraction object according to the specs below:
class SimpleFraction(object):
""" A number represented as a fraction """
def __init__(self, num, denom):
[Link] = num
[Link] = denom
def get_inverse(self):
""" Returns a float representing 1/self """
pass
def invert(self):
""" Sets self's num to denom and vice versa.
Returns None. """
pass
# Example:
f1 = SimpleFraction(3,4)
print(f1.get_inverse()) # prints 1.33333333 (note this one returns value)
[Link]() # acts on data attributes internally, no return
print([Link], [Link]) # prints 4 3
17
6.100L Lecture 18
LET’S TRY IT OUT WITH MORE
THINGS
f1 = SimpleFraction(3, 4)
f2 = SimpleFraction(1, 4)
print([Link]) 3
print([Link]) 4
print([Link](f2)) 1.0
print([Link](f2)) 0.1875
18
6.100L Lecture 18
SPECIAL OPERATORS IMPLEMENTED
WITH DUNDER METHODS
19
6.100L Lecture 18
SPECIAL OPERATORS IMPLEMENTED
WITH DUNDER METHODS
6.100L Lecture 18
PRINTING OUR OWN
DATA TYPES
21
6.100L Lecture 18
PRINT REPRESENTATION OF AN
OBJECT
>>> c = Coordinate(3,4)
>>> print(c)
<__main__.Coordinate object at 0x7fa918510488>
>>> print(c)
<3,4>
22
6.100L Lecture 18
DEFINING YOUR OWN PRINT
METHOD
class Coordinate(object):
def __init__(self, xval, yval):
self.x = xval
self.y = yval
def distance(self, other):
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
def __str__(self):
return "<"+str(self.x)+","+str(self.y)+">"
23
6.100L Lecture 18
WRAPPING YOUR HEAD AROUND
TYPES AND CLASSES
24
6.100L Lecture 18
EXAMPLE: FRACTIONS WITH
DUNDER METHODS
25
6.100L Lecture 18
CREATE & PRINT INSTANCES
class Fraction(object):
def __init__(self, n, d):
[Link] = n
[Link] = d
def __str__(self):
return str([Link]) + "/" + str([Link])
26
6.100L Lecture 18
LET’S TRY IT OUT
f1 = Fraction(3, 4)
f2 = Fraction(1, 4)
f3 = Fraction(5, 1)
print(f1) 3/4
print(f2) 1/4
print(f3) 5/1
Ok, but looks weird!
27
6.100L Lecture 18
YOU TRY IT!
Modify the str method to represent the Fraction as just the
numerator, when the denominator is 1. Otherwise its
representation is the numerator then a / then the denominator.
class Fraction(object):
def __init__(self, num, denom):
[Link] = num
[Link] = denom
def __str__(self):
return str([Link]) + "/" + str([Link])
# Example:
a = Fraction(1,4)
b = Fraction(3,1)
print(a) # prints 1/4
print(b) # prints 3
28
6.100L Lecture 18
IMPLEMENTING
+-*/
float()
29
6.100L Lecture 18
COMPARING METHOD vs.
DUNDER METHOD
30
6.100L Lecture 18
LETS TRY IT OUT
a = Fraction(1,4)
b = Fraction(3,4)
print(a) 1/4
c = a * b
print(c) 3/16
31
6.100L Lecture 18
CLASSES CAN HIDE DETAILS
32
6.100L Lecture 18
BIG IDEA
Special operations we’ve
been using are just
methods behind the
scenes.
Things like:
print, len
+, *, -, /, <, >, <=, >=, ==, !=
[]
and many others!
33
6.100L Lecture 18
CAN KEEP BOTH OPTIONS BY ADDING
A METHOD TO CAST TO A float
class Fraction(object):
def __init__(self, n, d):
[Link] = n
[Link] = d
………
def __float__(self):
return [Link]/[Link]
c = a * b
print(c) 3/16
print(float(c)) 0.1875
34
6.100L Lecture 18
LETS TRY IT OUT SOME MORE
a = Fraction(1,4)
b = Fraction(2,3)
c = a * b
print(c) 2/12
35
6.100L Lecture 18
ADD A METHOD
class Fraction(object):
………
def reduce(self):
def gcd(n, d):
while d != 0:
(d, n) = (n%d, d)
return n
if [Link] == 0:
return None
elif [Link] == 1:
return [Link]
else:
greatest_common_divisor = gcd([Link], [Link])
top = int([Link]/greatest_common_divisor)
bottom = int([Link]/greatest_common_divisor)
return Fraction(top, bottom)
c = a*b
print(c) 2/12
print([Link]()) 1/6 36
6.100L Lecture 18
WE HAVE SOME IMPROVEMENTS TO MAKE
class Fraction(object):
…………
def reduce(self):
def gcd(n, d):
while d != 0:
(d, n) = (n%d, d)
return n
if [Link] == 0:
return None
elif [Link] == 1:
s
return [Link]
else:
greatest_common_divisor = gcd([Link], [Link])
top = int([Link]/greatest_common_divisor)
bottom = int([Link]/greatest_common_divisor)
return Fraction(top, bottom)
37
6.100L Lecture 18
CHECK THE TYPES, THEY’RE DIFFERENT
a = Fraction(4,1)
b = Fraction(3,9)
ar = [Link]() 4
br = [Link]() 1/3
38
6.100L Lecture 18
YOU TRY IT!
Modify the code to return a Fraction object when denominator
is 1
class Fraction(object):
def reduce(self):
def gcd(n, d):
while d != 0:
(d, n) = (n%d, d)
return n
if [Link] == 0:
return None
elif [Link] == 1:
return [Link]
else:
greatest_common_divisor = gcd([Link], [Link])
top = int([Link]/greatest_common_divisor)
bottom = int([Link]/greatest_common_divisor)
return Fraction(top, bottom)
# Example:
f1 = Fraction(5,1)
print([Link]()) # prints 5/1
39
not 5
6.100L Lecture 18
WHY OOP and BUNDLING THE
DATA IN THIS WAY?
Code is organized and modular
Code is easy to maintain
It’s easy to build upon objects to make more complex objects
40
6.100L Lecture 18
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
41
INHERITANCE
(download slides and .py files to follow along)
6.100L Lecture 19
Ana Bell
1
WHY USE OOP AND
CLASSES OF OBJECTS?
Mimic real life
Group different objects part of the same type
Data attributes
How can you represent your object with data?
What it is
for a coordinate: x and y values
for an animal: age
Procedural attributes (behavior/operations/methods)
How can someone interact with the object?
What it does
for a coordinate: find distance between two
for an animal: print how long it’s been alive
6.100L Lecture 19
HOW TO DEFINE A CLASS (RECAP)
class Animal(object):
def __init__(self, age):
[Link] = age
[Link] = None
myanimal = Animal(3)
6.100L Lecture 19
GETTER AND SETTER METHODS
class Animal(object):
def __init__(self, age):
[Link] = age
[Link] = None
def __str__(self):
return "animal:"+str([Link])+":"+str([Link])
6.100L Lecture 19
GETTER AND SETTER METHODS
class Animal(object):
def __init__(self, age):
[Link] = age
[Link] = None
def __str__(self):
return "animal:"+str([Link])+":"+str([Link])
def get_age(self):
return [Link]
def get_name(self):
return [Link]
def set_age(self, newage):
[Link] = newage
def set_name(self, newname=""):
[Link] = newname
6.100L Lecture 19
AN INSTANCE and
DOT NOTATION (RECAP)
Instantiation creates an instance of an object
a = Animal(3)
Dot notation used to access attributes (data and methods)
though it is better to use getters and setters to access data
attributes
[Link]
a.get_age()
6.100L Lecture 19
INFORMATION HIDING
6.100L Lecture 19
CHANGING INTERNAL REPRESENTATION
class Animal(object):
def __init__(self, age):
[Link] = age
[Link] = None
def __str__(self):
return "animal:"+str([Link])+":"+str([Link])
def get_age(self):
return [Link]
def set_age(self, newage):
[Link] = newage
a.get_age() # works
[Link] # error
6.100L Lecture 19
PYTHON NOT GREAT AT
INFORMATION HIDING
11
6.100L Lecture 19
USE OUR NEW CLASS
def animal_dict(L):
""" L is a list
Returns a dict, d, mappping an int to an Animal object.
A key in d is all non-negative ints, n, in L. A value
corresponding to a key is an Animal object with n as its age. """
d = {}
for n in L:
if type(n) == int and n >= 0:
d[n] = Animal(n)
return d
L = [2,5,'a',-5,0]
12
6.100L Lecture 19
USE OUR NEW CLASS
L = [2,5,'a',-5,0]
animals = animal_dict(L)
print(animals)
13
6.100L Lecture 19
USE OUR NEW CLASS
def animal_dict(L):
""" L is a list
Returns a dict, d, mappping an int to an Animal object.
A key in d is all non-negative ints n L. A value corresponding
to a key is an Animal object with n as its age. """
d = {}
for n in L:
if type(n) == int and n >= 0:
d[n] = Animal(n)
return d
L = [2,5,'a',-5,0]
animals = animal_dict(L)
for n,a in [Link]():
print(f'key {n} with val {a}')
14
6.100L Lecture 19
YOU TRY IT!
Write a function that meets this spec.
def make_animals(L1, L2):
""" L1 is a list of ints and L2 is a list of str
L1 and L2 have the same length
Creates a list of Animals the same length as L1 and L2.
An animal object at index i has the age and name
corresponding to the same index in L1 and L2, respectively. """
#For example:
L1 = [2,5,1]
L2 = ["blobfish", "crazyant", "parafox"]
animals = make_animals(L1, L2)
print(animals) # note this prints a list of animal objects
for i in animals: # this loop prints the individual animals
print(i)
15
6.100L Lecture 19
BIG IDEA
Access data attributes
(stuff defined by [Link])
16
6.100L Lecture 19
HIERARCHIES
Parent class
(superclass) Animal
Child class
(subclass)
• Inherits all data and
behaviors of parent Person Cat Rabbit
class
• Add more info
• Add more behavior
• Override behavior Student
18
6.100L Lecture 19
INHERITANCE:
PARENT CLASS
class Animal(object):
def __init__(self, age):
[Link] = age
[Link] = None
def get_age(self):
return [Link]
def get_name(self):
return [Link]
def set_age(self, newage):
[Link] = newage
def set_name(self, newname=""):
[Link] = newname
def __str__(self):
return "animal:"+str([Link])+":"+str([Link])
19
6.100L Lecture 19
SUBCLASS CAT
20
6.100L Lecture 19
INHERITANCE:
SUBCLASS
class Cat(Animal):
def speak(self):
print("meow")
def __str__(self):
return "cat:"+str([Link])+":"+str([Link])
6.100L Lecture 19
WHICH METHOD
TO USE?
22
6.100L Lecture 19
SUBCLASS PERSON
23
6.100L Lecture 19
class Person(Animal):
def __init__(self, name, age):
Animal.__init__(self, age)
self.set_name(name)
[Link] = []
def get_friends(self):
return [Link]()
def add_friend(self, fname):
if fname not in [Link]:
[Link](fname)
def speak(self):
print("hello")
def age_diff(self, other):
diff = [Link] - [Link]
print(abs(diff), "year difference")
def __str__(self):
return "person:"+str([Link])+":"+str([Link])
24
6.100L Lecture 19
YOU TRY IT!
Write a function according to this spec.
def make_pets(d):
""" d is a dict mapping a Person obj to a Cat obj
Prints, on each line, the name of a person, a colon, and the
name of that person's cat """
pass
p1 = Person("ana", 86)
p2 = Person("james", 7)
c1 = Cat(1)
c1.set_name("furball")
c2 = Cat(1)
c2.set_name("fluffsphere")
d = {p1:c1, p2:c2}
make_pets(d) # prints ana:furball
# james:fluffsphere
25
6.100L Lecture 19
BIG IDEA
A subclass can
use a parent’s attributes,
override a parent’s attributes, or
define new attributes.
Attributes are either data or methods.
26
6.100L Lecture 19
SUBCLASS STUDENT
27
6.100L Lecture 19
import random
class Student(Person):
def __init__(self, name, age, major=None):
Person.__init__(self, name, age)
[Link] = major
def change_major(self, major):
[Link] = major
def speak(self):
r = [Link]()
if r < 0.25:
print("i have homework")
elif 0.25 <= r < 0.5:
print("i need sleep")
elif 0.5 <= r < 0.75:
print("i should eat")
else:
print("i'm still zooming")
def __str__(self):
return "student:"+str([Link])+":"+str([Link])+":"+str([Link])
28
6.100L Lecture 19
SUBCLASS RABBIT
29
6.100L Lecture 19
CLASS VARIABLES AND THE Rabbit
SUBCLASS
6.100L Lecture 19
RECALL THE __init__ OF Rabbit
[Link] 1
2
Age: 8
r1 Parent1: None
Parent2: None
r1 = Rabbit(8) Rid: 1
31
6.100L Lecture 19
RECALL THE __init__ OF Rabbit
[Link] 1
3
2
Age: 8
r1 Parent1: None
Parent2: None
r1 = Rabbit(8) Rid: 1
r2 = Rabbit(6)
Age: 6
r2 Parent1: None
Parent2: None
Rid: 2
32
6.100L Lecture 19
RECALL THE __init__ OF Rabbit
[Link] 1
3
2
4
Age: 8
r1 Parent1: None
Parent2: None
r1 = Rabbit(8) Rid: 1
r2 = Rabbit(6)
Age: 6
r3 = Rabbit(10) r2 Parent1: None
Parent2: None
Rid: 2
Age: 10
r3 Parent1: None
Parent2: None
Rid: 3
33
6.100L Lecture 19
Rabbit GETTER METHODS
class Rabbit(Animal):
tag = 1
def __init__(self, age, parent1=None, parent2=None):
Animal.__init__(self, age)
self.parent1 = parent1
self.parent2 = parent2
[Link] = [Link]
[Link] += 1
def get_rid(self):
return str([Link]).zfill(5)
def get_parent1(self):
return self.parent1
def get_parent2(self):
return self.parent2
34
6.100L Lecture 19
WORKING WITH YOUR OWN
TYPES
35
6.100L Lecture 19
RECALL THE __init__ OF Rabbit
[Link] 1
3
2
4
5
Age: 8
r1 Parent1: None
Parent2: None
Rid: 1
r1 = Rabbit(8) Age: 6
r2 = Rabbit(6) r2 Parent1: None
r3 = Rabbit(10) Parent2: None
Rid: 2
r4 = r1 + r2 Age: 10
r3 Parent1: None
Parent2: None
Rid: 3
Age: 0
Parent1: obj bound to r1
r4 Parent2: obj bound to r2
36
Rid: 4
6.100L Lecture 19
SPECIAL METHOD TO COMPARE TWO
Rabbits
Decide that two rabbits are equal if they have the same two
parents
def __eq__(self, other):
parents_same = ([Link] == [Link] and [Link] == [Link])
parents_opp = ([Link] == [Link] and [Link] == [Link])
return parents_same or parents_opp
Compare ids of parents since ids are unique (due to class var)
Note you can’t compare objects directly
For ex. with self.parent1 == other.parent1
This calls the __eq__ method over and over until call it on None and
gives an AttributeError when it tries to do None.parent1
37
6.100L Lecture 19
BIG IDEA
Class variables are
shared between all
instances.
If one instance changes it, it’s changed for every instance.
38
6.100L Lecture 19
OBJECT ORIENTED
PROGRAMMING
Create your own collections of data
Organize information
Division of work
Access information in a consistent manner
39
6.100L Lecture 19
MITOpenCourseWare
[Link]
For information about citing these materials or our Terms ofUse,visit: [Link]
40