Checkpoint: Core Syntax
Published by Brayan K
A checkpoint is a consolidation lesson that combines everything you've just learned — slicing, truthiness, None, ternaries, the walrus, match/case, unpacking, and sorting — into one realistic build.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Turn mixed records into a review queue
A review queue receives ticket records and notes. A ticket contains its tag, a name and a priority; notes must not enter the queue. Priorities are ranked from largest to smallest, with names breaking ties in ascending order. The report takes the first two ranked tickets and labels priorities of five or more urgent.
Start with well-formed data so the order of the operations is visible. Extract the tickets, order them, take a slice, then format the result. Each stage has a different job; changing their order can change the answer even when every individual expression is valid Python.
records = [("ticket", "Mira", 4), ("note", "desk opens soon"), ("ticket", "Noor", 0), ("ticket", "Ada", 9)]
tickets = []
for record in records:
match record:
case ["ticket", name, priority]:
tickets.append((name, priority))
case _:
pass
ranked = sorted(tickets, key=lambda row: (-row[1], row[0].casefold()))
for name, priority in ranked[:2]:
label = "urgent" if priority >= 5 else "routine"
print(name, priority, label)
# ✅ Expected output:
# Ada 9 urgent
# Mira 4 routineThis checkpoint owns the design of the pipeline, not a second introduction to its syntax. Structural Pattern Matching (match/case) and Unpacking & Star Expressions explain record shapes; Sorting with sorted() & key and Slicing Lists & Strings explain ranking and selection.
Do not unpack an unchecked record
A mixed feed can contain records with different lengths. An assignment that assumes three fields fails before your later condition has a chance to decide whether the record is a ticket. Put the shape decision before using the fields.
kind, name, priority = ("note", "maintenance")
if kind == "ticket":
print(name, priority)
# ✅ Expected error:
# ValueError: not enough values to unpack (expected 3, got 2)records = [("note", "maintenance"), ("ticket", "Mira", 4), ("ticket", "incomplete")]
for record in records:
match record:
case ["ticket", name, priority]:
print("ticket", name, priority)
case ["note", message]:
print("note", message)
case _:
print("invalid shape")
# ✅ Expected output:
# note maintenance
# ticket Mira 4
# invalid shapeA matching shape is still not a promise that the name is usable or the priority is numeric. Keep validation separate from the shape decision, then give every rejected record an explicit outcome. Silently skipping malformed input makes it hard to distinguish an empty queue from lost data.
Keep zero, absence and invalid data separate
The expanded contract allows None to mean “awaiting a priority”. Zero is a valid assigned priority. A filter that checks only truthiness removes both values, which loses a real ticket. Compare the two filters and trace which question each one asks.
tickets = [("Mira", 4), ("Noor", 0), ("Oli", None)]
truthy = [row for row in tickets if row[1]]
assigned = [row for row in tickets if row[1] is not None]
print("truthy:", truthy)
print("assigned:", assigned)
# ✅ Expected output:
# truthy: [('Mira', 4)]
# assigned: [('Mira', 4), ('Noor', 0)]Use None & NoneType for the absent-value contract and Booleans & Truthiness for choosing the predicate. A numeric text value or a negative priority is a different problem: reject it under this contract rather than quietly treating it as absent.
records = [("ticket", " Mira ", 4), ("ticket", "Noor", 0), ("ticket", "Oli", None), ("ticket", "", 3), ("ticket", "Bo", True)]
for record in records:
match record:
case ["ticket", str() as raw_name, priority] if (name := raw_name.strip()) and (priority is None or (type(priority) is int and priority >= 0)):
status = "waiting" if priority is None else "ready"
print(name, status)
case _:
print("rejected")
# ✅ Expected output:
# Mira ready
# Noor ready
# Oli waiting
# rejected
# rejectedThe guard records the stripped name once and requires it to be non-empty. The exact int check deliberately excludes bool. Capturing that cleaned value is covered by The Walrus Operator (:=); selecting a status value is covered by Conditional Expressions (Ternary).
Rank the eligible records before taking a prefix
Taking two rows before sorting answers “which of these two rows ranks highest?” Taking two rows after sorting answers “which two rows rank highest in the whole input?” Filtering, too, must happen before the limit if rejected records are not meant to use up places.
tickets = [("Mira", 4), ("Noor", 0), ("Ada", 9)]
key = lambda row: (-row[1], row[0].casefold())
print("limit first:", sorted(tickets[:2], key=key))
print("rank first:", sorted(tickets, key=key)[:2])
print("input:", tickets)
# ✅ Expected output:
# limit first: [('Mira', 4), ('Noor', 0)]
# rank first: [('Ada', 9), ('Mira', 4)]
# input: [('Mira', 4), ('Noor', 0), ('Ada', 9)]Keep the original feed available while building the report. sorted() gives this pipeline a separate outer list, so a caller can still inspect the arrival order. This is a design choice for the report, not a requirement that all programs avoid in-place sorting.
Complete the eligible-ticket selection
Fill the eligibility predicate and the two key fields. Exclude only None, rank higher priorities first and use case-insensitive names for ties. Keep the final slice after both filtering and ranking.
tickets = [("Zoe", 0), ("Ada", 8), ("Oli", None), ("Ben", 8)]
eligible = [row for row in tickets if ___]
ranked = sorted(eligible, key=lambda row: (___, ___))
print("eligible:", len(eligible))
print(ranked[:2])
# 👉 replace ___ with row[1] is not None
# 👉 replace ___ with -row[1]
# 👉 replace ___ with row[0].casefold()
# ✅ Expected output:
# eligible: 3
# [('Ada', 8), ('Ben', 8)]Deliver the queue with rejection counts
Extend the program to use the input below. A valid record has exactly three fields: the literal ticket tag, a non-blank string name, and either None or a non-negative integer priority. Reject booleans as priorities. Strip names once, hold records with absent priorities separately, and retain valid zeroes in the ready queue.
Print counts labelled ready, waiting and rejected. Then print at most two ready tickets ranked by priority descending and case-insensitive name ascending, with an urgent/routine label using the earlier threshold. Finally print the original first record so you can check that cleaning did not modify the source. Try writing this as separate validation, ranking and reporting stages before reading the solution.
records = [
("ticket", " Mira ", 4), ("ticket", "Noor", 0),
("ticket", "Ada", 9), ("ticket", "Oli", None),
("ticket", "", 3), ("ticket", "Bo", True), ("ticket", "unfinished"),
]
ready = []
waiting = []
rejected = 0
for record in records:
match record:
case ["ticket", str() as raw_name, priority] if (name := raw_name.strip()) and (priority is None or (type(priority) is int and priority >= 0)):
if priority is None:
waiting.append(name)
else:
ready.append((name, priority))
case _:
rejected += 1
ranked = sorted(ready, key=lambda row: (-row[1], row[0].casefold()))
print("ready:", len(ready))
print("waiting:", len(waiting))
print("rejected:", rejected)
for name, priority in ranked[:2]:
label = "urgent" if priority >= 5 else "routine"
print(name, priority, label)
print("source:", records[0])
# ✅ Expected output:
# ready: 3
# waiting: 1
# rejected: 3
# Ada 9 urgent
# Mira 4 routine
# source: ('ticket', ' Mira ', 4)Check the boundary cases by changing one record at a time: an empty feed, two equal priorities, a blank name, a zero, an absent priority and an extra field. The contract tells you which group each belongs to. A program is easier to trust when these decisions are visible rather than hidden inside one large expression.
Practice quiz
What does this program print? rows = [4, 0, 9] print(sorted(rows[:2], reverse=True)) print(sorted(rows, reverse=True)[:2])
- [9, 4] [9, 4]
- [4, 0] [9, 4]
- [4, 0] [4, 0]
- [0, 4] [4, 9]
Answer: [4, 0] [9, 4]. The earlier slice removes a contender before the first sort can see it.
What does this program print? values = [None, 0, 4] print([n for n in values if n is not None])
- [4]
- [None, 4]
- [None, 0, 4]
- [0, 4]
Answer: [0, 4]. An explicit absence test retains the valid zero.
What does this program print? match ("ticket", "Ada"): case ["ticket", name, priority]: print(name) case _: print("reject")
- reject
- Ada
- ValueError
- None
Answer: reject. A nonmatching sequence pattern falls through instead of raising an unpacking error.
What does this program print? name, *tags, status = ("Ada", "ready") print(name, tags, status)
- Ada None ready
- Ada () ready
- Ada [] ready
- ValueError
Answer: Ada [] ready. The star collects an empty list between the required boundary fields.
What does this program print? priority = 0 print("waiting" if priority is None else "ready")
- waiting
- ready
- False
- None
Answer: ready. The condition asks about absence, not the truthiness of the number.
What does this program print? raw = " Ada " if name := raw.strip(): print(name) print(raw == name)
- Ada True
- Ada True
- NameError
- Ada False
Answer: Ada False. The captured stripped string is separate from the unchanged source string.
What does this program print? rows = [("Zoe", 4), ("Ada", 4), ("Mira", 6)] print(sorted(rows, key=lambda row: (-row[1], row[0]))[:2])
- [('Mira', 6), ('Ada', 4)]
- [('Mira', 6), ('Zoe', 4)]
- [('Ada', 4), ('Zoe', 4)]
- [('Zoe', 4), ('Ada', 4)]
Answer: [('Mira', 6), ('Ada', 4)]. The key applies both ranking rules before the prefix is selected.
What does this program print? values = [3, 1] ranked = sorted(values) ranked.append(5) print(values) print(ranked)
- [1, 3, 5] [1, 3, 5]
- [3, 1, 5] [1, 3, 5]
- [3, 1] [1, 3, 5]
- [1, 3] [1, 3, 5]
Answer: [3, 1] [1, 3, 5]. The sorted result is a separate outer list, so appending to it does not append to the input.
Continue this course
- Previous: Sorting with sorted() & key
- Next: functools: lru_cache, partial, reduce — Memoize with lru_cache, pre-fill args with partial, and fold with reduce
- Quick reference: Python cheat sheet