Lecture 6: October 15, 2019
Reading
: §4, 6
Due
: Homework 2, due on October 24 at 11:59pm
Greetings and felicitations!
In more detail: how Python does function calls [
quad.py
]
Caller suspends execution at point of call, remembers where it left off
Formal parameters assigned values from actual parameters
Execute function body
Return control to where caller left off
Refactoring code
Compute the perimeter of a triangle [
peri0.py
]
Collapse similar statements: make the distance between 2 points a function [
peri1.py
]
Collapse similar statements: make the prompts a function [
peri2.py
]
Refactor for clarity only: make the perimeter computation a function [
peri3.py
]
Add error checking: “peri0.py” done right [
peri-c.py
]
Add error checking: “quad.py” done right [
quad-c.py
]
Sequences
Sequences are a series of values in a particular order
In Python predominantly strings and lists but also sets and tuples
Strings
Sequence of characters (characters are strings of length 1)
Strings are immutable; really important for functions
Basic string operations
+
, concatenation for strings
*
, repetition repeats given value
len()
returns length of sequence
s in str
returns
True
if
s
is a substring of
str
,
False
otherwise
Indexing,
var[position]
Count from 0 to
len(var)
−1
Position can be a negative number to count from right
Assignment with indexing doesn’t work as strings immutable
x = ’hEllo’; x[1] = ’e’
produces an error
Slicing,
var[start:end]
Value at index end not included in slice
If omitted, starting value defaults to 0 and ending value defaults to last index + 1
Can use negative index
Looping over strings:
for i in str
Example program [
strstuff.py
]
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email:
[email protected]
MISSING TITLE
Version of October 15, 2019 at 6:40PM
You can also obtain a PDF version of this.