Learning objectives
You know functions, conditionals, map, filter, sort, and datatypes from Pyret. You also know how to write test cases. In this lab, you practice these concepts in Python, and also get experience with Python errors.
This lab will:
- give you practice writing functions, conditionals, and higher-order list functions in Python;
- introduce dataclasses, Python's version of a Pyret datatype;
- teach you to read Python error messages, especially the ones caused by a missing
returnor bad indentation; and - have you write tests in
pytest.
Set up Python in VS Code
- Install Python 3.12 or newer from python.org. On a Mac, use this installer rather than the Python that came with your computer, which is too old. On Windows, tick "Add python.exe to PATH" on the first screen of the installer.
- Install the Python extension in VS Code: open the Extensions panel, search for Python (published by Microsoft), and install it.
- Open a folder, not a single file: File → Open Folder, and make a new folder for this lab. Then open the command palette (Cmd+Shift+P, or Ctrl+Shift+P on Windows), run Python: Select Interpreter, and pick the Python you installed in step 1 (the one with the highest version number).
- Install pytest. Open a terminal in VS Code (Terminal → New
Terminal) and run
python3 -m pip install pytest. On Windows, usepyin place ofpython3, here and everywhere below. - Check that it works. In your folder, create a file
test_check.pycontaining:
Rundef test_check(): assert 1 + 1 == 2python3 -m pytestin the terminal. You should see1 passed. If so, you're done.
Note: Always run tests as python3 -m pytest, not just
pytest. It works even when your computer can't find the
pytest command. If a python3 command says "not found" or
"command not recognized", Python isn't on your PATH: on Windows, rerun the
installer and tick the PATH box; otherwise, ask a TA.
Setup
- Find a partner. Labs are pair work.
- Download the starter files and unzip them into a
folder you can open in VS Code. You'll work in
voting.pyandtest_voting.py; the other files are for Part 2. - Run tests with
python3 -m pytest(py -m pyteston Windows) in a terminal, from the folder with your files. Every task says what value you should see. - There is no worksheet for this lab
Pyret to Python cheat sheet
| Pyret | Python |
|---|---|
fun f(x): body end | def f(x): then an indented body with an explicit return |
if c: a else if d: b else: e end | if c: / elif d: / else:, each with an indented body |
member(lst, x) | x in lst |
length(lst) | len(lst) |
lam(x): body end | lambda x: body |
map(f, lst) | list(map(f, lst)) |
filter(f, lst) | list(filter(f, lst)) |
| sort by a key | sorted(lst, key=f); add reverse=True for descending |
lst.get(0) | lst[0] |
num-abs(n) | abs(n) |
check: f(1) is 2 end | def test_f(): then assert f(1) == 2 |
Part 1Warm-up
In the same directory where you opened the starter files, create a file test_warmup.py:
def double(n):
return n * 2
def test_double():
assert double(4) == 8
Run python3 -m pytest test_warmup.py. Then change the 8 to 9 and run again. Find in the output the line that failed and the value double(4) actually produced. (Pytest only runs functions whose names start with test_.)
Part 2From Pyret to Python
Put these functions in voting.py and a test for each in test_voting.py. Use assert to write the functions as we did in class. The list CANDIDATES is already defined in voting.py.
Is this a valid vote? "Ben" should be valid; "Zed" and "" should not.
fun is-valid-vote(v :: String) -> Boolean:
member(CANDIDATES, v)
endCompute how many votes a candidate got? Expect 3 for "Ada" in ["Ada","Ben","Ada","Cy","Ada"].
fun count-for(votes :: List<String>, cand :: String) -> Number:
length(filter(lam(v): v == cand end, votes))
end
Before you fix anything: what happens if you leave out the list(...) that Python requires around filter?
Produce a label for the margin of victory. The function should return "comfortable" on 100, "close" on 10, and "landslide" on 101. Write at least one boundary test.
fun margin-label(n :: Number) -> String:
if n > 100: "landslide"
else if n > 10: "comfortable"
else: "close"
end
endCheckpoint
Show a TA your three functions and their tests passing.
Part 3Reading error messages
We've created several files with broken code. Don't read the code first. For each file, run pytest, read the message, and write down your answers before editing. Then fix the code.
Step 1Missing and misplaced returns
Run python3 -m pytest test_buggy_returns.py. It has five bugs. For each failing test, make a note of the issue:
| Test | The message (short) | Which line does it point to? | What was actually wrong? |
|---|---|---|---|
test_majority_needed | |||
test_lead_is_safe | |||
test_turnout_label | |||
test_lead_label | |||
test_count_ballots |
Discuss with your partner, and make note of your answers (just on paper, no worksheet this week):
- Several messages mention
None. What isNone, and when does Python hand you one? - In
test_lead_is_safe, the error points intolead_is_safe, but the bug is in a different function. How would you track down the real culprit? turnout_labelandlead_labelboth giveNonefor some inputs, for different reasons. Explain each in a sentence. Why didn't Python complain about the line"low"or the line after the firstreturn?- What does
object of type 'filter' has no len()tell you to do?
Fix all five bugs. Every test in the file should pass.
Checkpoint
Show a TA your filled-in table and your fixed file.
Step 2Indentation errors
The files test_indent1.py, test_indent2.py, and test_indent3.py fail before any test runs, because Python can't even read them. For each: predict the message from the code, run pytest, compare, then fix. Answer:
- What does the message name, and what line number does it give? Is that the line that is wrong, or the line where Python gave up?
- In
test_indent3.py, what does "outer indentation level" mean? Draw the indentation of each line as a column of numbers.
Note: Your Python version may print a longer message, such as "expected an indented block after 'if' statement". Same bug.
Step 3Break it yourself
Take your working is_valid_vote. Make each change below, predict what pytest will say, then check. Undo each before the next.
- Delete the word
return. - Indent the
returnline two extra spaces. - Put
returnat the same indentation asdef. - Replace
==with=somewhere in anif.
Checkpoint
Tell a TA which of your predictions were wrong.
Part 4Writing code from scratch
Continue working in voting.py and test_voting.py. For each task, write the tests first: use the expected values given, add your own, and watch them fail. Then write the function. A function with no return fails its tests; that's what tests are for.
percent_for(votes, cand): the percent (0–100) of votes that went to cand. With no votes at all, answer 0 (don't divide by zero). Expect 75.0 for "Ada" in ["Ada","Ada","Ben","Ada"].
valid_votes(votes, candidates): just the votes that name a candidate. Expect ["Ada","Ben"] from ["Ada","Zed","","Ben"].
ranking(votes, candidates): the candidates ordered from most to fewest votes. Use sorted with a key. Expect ["Cy","Ben","Ada"] for ["Cy","Cy","Ben"]. What order do you get with an empty list of votes? Is that a tie-break you chose, or one Python chose?
Hint: sorted(lst, key=f, reverse=True) orders lst by the
value f gives for each element, largest first. For example,
sorted(["pear", "fig", "banana"], key=lambda w: len(w), reverse=True)
produces ["banana", "pear", "fig"]: longest word first. Here, what
should the key function compute for a candidate?
election_result(votes, candidates): the winner's name, or "tie" if the top two have equal counts, or "no votes" if there are no valid votes. Use only functions you've already written. Expect "Ada" for ["Ada","Ben","Ada"], "tie" for ["Ada","Ben"], and "no votes" for ["Zed",""].
Note: Python lets you name an intermediate result inside a function
(ranked = ranking(...)), just like name = expr in a Pyret
function body.
Part 5Voters as dataclasses
Note: Kathi designed the lab but used Claude to help generate the handout. Some of the wording in this section may still be a bit odd. Apologies in advance that Kathi ran out of time to finish checking and polishing the handout language.
Pre-existing Pyret code:
data Voter:
| voter(name :: String, id :: Number, party :: String, choice :: String)
end
choice is "" if the voter didn't vote. A dataclass is how Python gives you a datatype like this. Here is one for a different record:
from dataclasses import dataclass
@dataclass
class Precinct:
name: str
registered: int
p = Precinct("Ward 3", 1200) # construct: like Pyret's precinct("Ward 3", 1200)
p.registered # access a field: like Pyret's p.registered
In the Python console (run python3), paste in the Precinct definition. Then predict, and try, each of these:
Precinct("Ward 3")
Precinct("Ward 3", "lots")
p.regsitered
Precinct("Ward 3", 1200) == Precinct("Ward 3", 1200)
Which of these would Pyret have caught that Python didn't? What do the str and int after the colons actually do? What does that mean for your tests?
Our answers (open after you've tried)
The first is a TypeError about a missing argument. The second runs fine: the annotations are documentation, not checks. The third is an AttributeError. The fourth is True: dataclasses compare field by field, so you can use == on whole values in tests. And since Python won't catch a wrong type, your tests have to.
Define Voter in voting.py, and paste these into the VOTERS list. Expect VOTERS[0].party to be "Green".
Voter("Mia", 101, "Green", "Ada")
Voter("Joe", 102, "Gold", "Ben")
Voter("Lena", 103, "Blue", "Ada")
Voter("Omar", 104, "Green", "")
Voter("Pat", 105, "Gold", "Ben")
Voter("Quinn", 106, "Green", "Ada")
Voter("Ravi", 107, "Blue", "Cy")
Voter("Sol", 108, "Gold", "Cy")For the rest of this part, write the tests first, then the code. Use VOTERS and == on whole Voter values in your tests, for example voters_of_party(VOTERS, "Green") == [VOTERS[0], VOTERS[3], VOTERS[5]].
voted(v): did this voter cast a vote? Mia yes, Omar no. Also party_of(candidate): Ada is "Green", Ben "Gold", Cy "Blue", anyone else "none".
crossed_party(v): did the voter vote for a candidate of a different party than their own? Lena and Sol are the only two in VOTERS. (Abstainers don't cross.) Then crossover_count(voters): expect 2.
voters_of_party(voters, party) (expect three Green voters) and names_alphabetical(voters): names only, sorted. Expect ["Joe","Lena","Mia","Omar","Pat","Quinn","Ravi","Sol"].
votes_from_party(voters, party): the choices of the voters in that party who voted. Expect ["Ada","Ada"] for Green (Omar didn't vote) and ["Ben","Ben","Cy"] for Gold.
overall_winner(voters): reuse election_result from the previous part. Expect "Ada".
Hint: You need a list of strings from a list of Voters. Which
higher-order function turns one list into another of the same length?
Checkpoint
Show a TA your Voter tests passing.
Additional features
Everything below here is optional.
Optional
party_turnout(voters, party): the percent of the party's members who voted. Gold is 100.0; Green is two thirds. Look up pytest.approx to test the Green case.
One last thing
In Python, a function can quietly return nothing, and a field labeled int can quietly hold a string. Nothing was wrong with your syntax in either case; the program just did something other than what you meant. The tests were the only thing in this lab that noticed.
Getting help
In lab, flag down a TA. You do not have to be stuck to do it, and you do not have to have tried everything first — that is what they are in the room for. Ask early: a pair that spends forty minutes on a typo has lost the part of the lab that was worth doing.
Your partner counts too. Saying out loud what you think the code does is most of debugging, and it is faster than waiting.
After lab, short questions go on Ed, and anything longer is better brought to office hours.
Comments or concerns?
If you have comments or concerns, submit them on the anonymous feedback form. Sign in with your Brown Google account to open it; your email address is not recorded.