Python primer for the case files

The small amount of Python that the case-file labs need, with a tiny example of each idea: variables, lists, dictionaries, loops, functions, reading JSON and CSV, sorting, sets, dates, and the mistakes that cost the most time. About an hour, and every example runs in the lab.

The case-file labs ask you to write a little Python that reads files and works out an answer. You do not need to be a programmer. You need about ten ideas, and this page has all of them. Type each example into a lab editor (any case file will do) and press Run: reading is not enough, your fingers must learn it.

How a lab works, in one minute

Your files are already in the lab’s folder. Your script reads them, works something out, and leaves the answers in variables or functions with the names that the starter gives you. Check my answers then looks at those names. Nothing needs to be printed, but print(...) is the way to look at what you have.

1. Variables and the basic types

count = 12            # a whole number
rate = 0.25           # a number with a decimal point
name = "Kano"         # text
ok = True             # True or False
nothing = None        # "no value yet" (the starters use it for the answers you must fill in)

print(count, name) shows them. In a lab, None means “replace me with your answer”.

2. Lists

cities = ["Lagos", "Abuja", "Kano"]
cities[0]              # "Lagos" (counting starts at 0)
cities[-1]             # "Kano" (the last one)
len(cities)            # 3
cities.append("Enugu") # add one at the end
sorted(cities)         # a new list in alphabetical order
sum([3, 4, 5])         # 12

3. Dictionaries (a name and its value)

stock = {"cables": 40, "routers": 7}
stock["routers"]            # 7
stock["switches"] = 12      # add or change
stock.get("printers", 0)    # 0 when the key is missing, instead of an error
"cables" in stock           # True
list(stock.keys())          # ["cables", "routers", "switches"]

4. Loops and conditions

total = 0
for item in [3, 4, 5]:
    if item > 3:
        total = total + item
    elif item == 3:
        total = total + 1
    else:
        total = total + 0
print(total)               # 10

Indentation (four spaces) is how Python knows what belongs inside the loop or the if. A comparison uses ==, !=, <, <=, >, >=. Combine tests with and, or, not.

big = [x for x in [3, 4, 5, 6] if x > 4]     # a list built in one line: [5, 6]

5. Functions

def add_tax(price, rate=0.075):
    """Return the price with tax."""
    return price * (1 + rate)

add_tax(100)               # 107.5

A function takes inputs, returns one answer and ends. In the labs, a function that you write is also tested on data that you cannot see, so write it for any data, and think about the empty case (an empty list, no rows).

6. Reading files

import json, csv

data = json.load(open("groups.json"))      # a JSON file becomes lists and dicts

with open("tickets.csv") as f:
    rows = list(csv.DictReader(f))         # each row is a dict: rows[0]["priority"]

text = open("notes.txt").read()
lines = text.splitlines()

CSV values are always text: int(row["minutes"]) makes a number. Strip spaces with row["name"].strip().

7. Sorting, sets and counting

sorted([3, 1, 2])                          # [1, 2, 3]
sorted(people, key=lambda p: p["age"])     # sort dicts by a field
sorted(people, key=lambda p: (-p["score"], p["name"]))   # highest score first, ties by name
unique = set([1, 2, 2, 3])                 # {1, 2, 3}: a set holds each value once
counts = {}
for word in ["a", "b", "a"]:
    counts[word] = counts.get(word, 0) + 1 # {"a": 2, "b": 1}

8. Text and numbers

f"{name} has {count} items"                # "Kano has 12 items"
"a,b,c".split(",")                         # ["a", "b", "c"]
"  hello ".strip().upper()                 # "HELLO"
round(3.14159, 2)                          # 3.14
17 // 5                                    # 3 (whole-number division)
17 % 5                                     # 2 (the remainder)

9. Dates and times

from datetime import date, datetime

d = date.fromisoformat("2026-11-10")
(date(2026, 11, 10) - date(2026, 8, 12)).days      # 90
d.weekday()                                          # 0 is Monday, 6 is Sunday
t = datetime.fromisoformat("2026-11-06T04:30")
(datetime(2026, 11, 6, 9, 30) - t).total_seconds() // 60   # minutes between two times

10. Reading errors

When your code fails, the last line of the message says what, and the line above it says where. The common ones:

Message Usually means
NameError: name 'x' is not defined a typo, or you used a variable before you made it
KeyError: 'name' the dict has no such key: use .get("name") or check in first
TypeError: unsupported operand you mixed text and numbers: int("5") + 1
IndentationError the spaces at the start of a line are wrong
IndexError: list index out of range the list is shorter than you thought (maybe empty)

Mistakes that cost the most time

  • Edges. Test the empty case, the exact limit (is “more than 30” 30 or 31?) and a tie. The labs test them on data you cannot see.
  • Changing a list while looping over it. Build a new list instead.
  • Forgetting that CSV values are text. "10" < "9" is true for text.
  • Comparing floats for equality. Use round(x, 2) or compare with a tolerance.
  • Returning None by accident. A function without return returns None.

Try it

Open any case file, and in the editor write a script that reads the first file and prints how many rows or keys it has: print(len(data)). If that runs, you are ready.