Quiz 7: Files, Exceptions, List Comprehensions, Sorting
Learning Goals
Students should be able to:
For files:
- Open files in different modes using Python's
openfunction - Close files in using Python's
closefunction - Use Python's
with ... assyntax for opening and closing files. - Read data from files by using a
forloop to iterate over a file (the preferred method, which iteraties over the lines of the file), but also by using the.read,.readlinesand.readlinemethods (where appropriate). - Write data to files using the
.writemethod - Explain the difference between reading, writing, and appending files
- Understand how programs create and modify files
- Remove leading and trailing whitespace from a string (including newlines)
using the
.stripmethod. - Split a string into lists of strings using the
.splitmethod
For exceptions
- Explain the behavior of code that uses
try/exceptto handle exceptions. - Write code that uses
try/exceptto implement specified exception handling behavior.
For list comprehensions:
- Translate between
forloops and list comprehensions - Use list comprehension expressions to concisely create lists using the mapping and/or filtering patterns.
For sorting
- Understand the difference between
sortedand.sortwhen reading and writing code involving sorting. - Understand how strings and (possibly nested) tuples are sorted by
sortedand.sort, both in ascending order (the default, when implicitlyreverse=False) and in descending order (whenreverse=True) - Understand how the
keykeyword parameter of bothsortedand.sortcan be used in conjunction with a function (specified either by a helper function or by alambdaexpression) to change the default order in which the values in a sequence of are sorted. - Use the above knowledge to read and write code involving sorting.
Study Guide
Blank (fill in your solutions)
Solutions
After your quiz is graded by instructors, you will get an email from Gradescope. Solutions for individual quiz questions are provided in the Gradescope rubric.