Lecture 11: Contexts, Comprehensions, and Test 1 Prep
Topics
Contexts
This is an extra topic on which you won't be tested.
There's a bug in this function; what is it?
def read_file_lines(path : str) -> List[str]: f = open(path, 'r') lines = [] for line in f: lines.append(line.strip()) return lines
- Didn't close f!
Here's another function:
def is_line_in_file(path : str, line : str) -> bool: f = open(path, 'r') for this_line in f: if this_line.strip() == line: return True f.close() return False
- It also has a bug! What is it?
- Doesn't always close f!
- It also has a bug! What is it?
Here's yet another function:
def is_num_in_file(path : str, num : float) -> bool: f = open(path, 'r') for this_line in f: if float(this_line.strip()) == num: f.close() return True f.close() return False
- It also has a bug! What is it?
- Doesn't always close f!
float(str)
can throw an error!
- It also has a bug! What is it?
with ... as binding:
- A new kind of control structure
- The
...
creates a resource like an open file, calling itbinding
- Open files are tracked by the OS with "file handles"
- There is a limited number of these available!
- Files (and other scarce resources like them, which Python calls "context managers") implement two methods:
__enter__()
__exit__()
- These get called on going into the
with
and on leaving thewith
- Either because of control moving past the end, or because of a return! Or even an error!
with
is a safe way to use these without worrying about doing the cleanup
Student Presentation
Self appraisal quiz: mystery recursive function
def rec_mystery(l): # assumes list has at least one element if len(l) == 1: return l[0] else: m = rec_mystery(l[1:]) if m > l[0]: return m else: return l[0]
Midterm prep
Notes
- You can bring two pages of notes
- Two single sided sheets
- One double sided sheet
Structure
True/False
Finding and fixing bugs
Writing some code
What's going on?
Iteration
Content
- Everything before recursion
- print vs return
- aliasing
- math operations
in-place update operators:
x = 0 x += 1 # x = x + 1 y = 100 y *= x # y = y * x # + * / - have these versions s = "hello" s += " hi" # --> "hello hi"
- fundamental control structures (syntax)
- slicing and sequences, sequence operators
- differences between types of sequences
- be able to read a specification and implement some code
- be able to read some code and come up with a plain language specification (e.g. function name, how you'd explain it to a non-programmer)
List Comprehensions
This is an extra topic on which you won't be tested.
- We can quit writing that same for loop over and over and use list comprehensions instead (please see the reading for examples).