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:

Set up Python in VS Code

  1. 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.
  2. Install the Python extension in VS Code: open the Extensions panel, search for Python (published by Microsoft), and install it.
  3. 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).
  4. Install pytest. Open a terminal in VS Code (Terminal → New Terminal) and run python3 -m pip install pytest. On Windows, use py in place of python3, here and everywhere below.
  5. Check that it works. In your folder, create a file test_check.py containing:
    def test_check():
        assert 1 + 1 == 2
    Run python3 -m pytest in the terminal. You should see 1 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

Pyret to Python cheat sheet

PyretPython
fun f(x): body enddef f(x): then an indented body with an explicit return
if c: a else if d: b else: e endif c: / elif d: / else:, each with an indented body
member(lst, x)x in lst
length(lst)len(lst)
lam(x): body endlambda x: body
map(f, lst)list(map(f, lst))
filter(f, lst)list(filter(f, lst))
sort by a keysorted(lst, key=f); add reverse=True for descending
lst.get(0)lst[0]
num-abs(n)abs(n)
check: f(1) is 2 enddef test_f(): then assert f(1) == 2

Part 1Warm-up

Task 1

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.

Task 2

Is this a valid vote? "Ben" should be valid; "Zed" and "" should not.

fun is-valid-vote(v :: String) -> Boolean:
  member(CANDIDATES, v)
end

Task 3

Compute 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?

Task 4

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
end

Checkpoint

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

Task 5

Run python3 -m pytest test_buggy_returns.py. It has five bugs. For each failing test, make a note of the issue:

TestThe 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

Task 6

Discuss with your partner, and make note of your answers (just on paper, no worksheet this week):

  1. Several messages mention None. What is None, and when does Python hand you one?
  2. In test_lead_is_safe, the error points into lead_is_safe, but the bug is in a different function. How would you track down the real culprit?
  3. turnout_label and lead_label both give None for some inputs, for different reasons. Explain each in a sentence. Why didn't Python complain about the line "low" or the line after the first return?
  4. What does object of type 'filter' has no len() tell you to do?

Task 7

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

Task 8

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

Task 9

Take your working is_valid_vote. Make each change below, predict what pytest will say, then check. Undo each before the next.

  1. Delete the word return.
  2. Indent the return line two extra spaces.
  3. Put return at the same indentation as def.
  4. Replace == with = somewhere in an if.

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.

Task 10

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"].

Task 11

valid_votes(votes, candidates): just the votes that name a candidate. Expect ["Ada","Ben"] from ["Ada","Zed","","Ben"].

Task 12

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?

Task 13

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.

Checkpoint

Show a TA your tie-case tests for Task 12 and Task 13.

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

Task 14

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.

Task 15

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]].

Task 16

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".

Task 17

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.

Task 18

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"].

Task 19

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.

Task 20

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.