Code your teammates can follow
How to write SQL and Python that a reviewer can check in ten minutes and a teammate can pick up next month. For students heading into data and analytics exams, take-homes and first jobs, including notebooks and Hex. The SQL runs in your browser on made-up data.
- Why it mattersThe reviewer and the teammate
- SQL styleTen rules, before and after
- Python styleNine habits for pandas
- Notebooks and HexThe order a reader needs
- Refactor thisThree exercises and a scorecard
- ChecklistOne page to print
1 Why it matters
Two people read your code more carefully than anyone else will.
- The reviewer of your take-home. They have a pile of submissions and maybe ten minutes for yours. In the first minute they decide whether they can follow it. If they cannot, they stop looking for the good parts.
- The teammate who inherits it. In a first job, your query gets rerun next month by someone else, or by you after you have forgotten it. If they cannot tell what a step does, they rewrite it, or worse, trust it.
Readable code lets someone else check your work quickly. Same query, both ways:
Hard to check
Show the result without running
| plan | count(*) | round(avg(x.c),1) |
|---|---|---|
| premium | 6 | 17.3 |
| free | 8 | 7.6 |
Easy to check
Show the result without running
| plan | listeners | avg_full_plays |
|---|---|---|
| premium | 6 | 17.3 |
| free | 8 | 7.6 |
Same result both ways: 2 rows, 3 columns.
Both are correct. Only the second can be checked in a minute: the reader sees what a play is, what one row means, and what each number is called.
This page covers style rules for SQL and Python, how to lay out a notebook or a Hex project, three refactoring exercises, and a checklist you can print. The SQL boxes run in your browser on the same made-up data as CTEs: write SQL in steps. The Python is shown as code to read. Every before and after pair was run, and gives the same result unless it says otherwise.
2 SQL style
Most rules have a BAD and a GOOD version that return the same result. Style changes how a query reads, never what it returns. If your tidy-up changes the result, you have changed the logic.
1. One clause per line
The eye finds SELECT, FROM, WHERE and GROUP BY down the left edge. Long lists of columns get one column per line.
BAD
Show the result without running
| category | products | avg_price |
|---|---|---|
| Outdoor | 3 | 84.83 |
| Kitchen | 3 | 58.67 |
| Games | 1 | 34.99 |
| Books | 2 | 31.0 |
GOOD
Show the result without running
| category | products | avg_price |
|---|---|---|
| Outdoor | 3 | 84.83 |
| Kitchen | 3 | 58.67 |
| Games | 1 | 34.99 |
| Books | 2 | 31.0 |
Same result both ways: 4 rows, 3 columns.
2. Pick a keyword case and stick to it
UPPERCASE keywords with lowercase names is the most common choice, and the one used across this site. Lowercase everything is fine too. Mixing is not: it looks like three people wrote it.
BAD
Show the result without running
| name | city |
|---|---|
| Aisling Keane | Dublin |
| Aoife Byrne | Dublin |
| Ciara Brennan | Dublin |
| Fionn Daly | Dublin |
| Meabh Carroll | Dublin |
| Padraig Healy | Dublin |
| Saoirse Doyle | Dublin |
GOOD
Show the result without running
| name | city |
|---|---|
| Aisling Keane | Dublin |
| Aoife Byrne | Dublin |
| Ciara Brennan | Dublin |
| Fionn Daly | Dublin |
| Meabh Carroll | Dublin |
| Padraig Healy | Dublin |
| Saoirse Doyle | Dublin |
Same result both ways: 7 rows, 2 columns.
SQLite does not care about case in names, so both run. A reader does.
3. Names that say what they hold
Step names and column names are the documentation nobody has to write separately. t1, cnt and x make the reader work it out every time.
BAD
Show the result without running
| title | cnt |
|---|---|
| Blue Hour | 1 |
| Ferry Home | 1 |
| Kite Weather | 1 |
| Night Bus | 1 |
| Wild Garlic | 1 |
GOOD
Show the result without running
| title | skips |
|---|---|
| Blue Hour | 1 |
| Ferry Home | 1 |
| Kite Weather | 1 |
| Night Bus | 1 |
| Wild Garlic | 1 |
Same result both ways: 5 rows, 2 columns.
With the bad version you have to read the WHERE to learn the count is skips. With the good one the name tells you.
4. Aliases that mean something
a, b, c force the reader to scroll up for every column. Use a short form of the table name: o for orders, p for products, c for customers.
BAD
Show the result without running
| name | units |
|---|---|
| Cookbook: Brown Bread | 6 |
| Cast Iron Pan | 5 |
| Atlas of Islands | 2 |
| Rain Jacket | 2 |
| Trail Runner Shoes | 2 |
| Novel: Low Tide | 1 |
GOOD
Show the result without running
| name | units |
|---|---|
| Cookbook: Brown Bread | 6 |
| Cast Iron Pan | 5 |
| Atlas of Islands | 2 |
| Rain Jacket | 2 |
| Trail Runner Shoes | 2 |
| Novel: Low Tide | 1 |
Same result both ways: 6 rows, 2 columns.
Write AS before each alias, too. It is optional, but it makes the alias easy to spot.
5. Leading or trailing commas: choose one
Both are fine. Leading commas make it easy to comment out a line and see a missing comma. Trailing commas read more like normal writing. Teams pick one; follow your team.
Trailing (used on this site)
SELECT customer_id,
name,
city
FROM customers;Leading
SELECT customer_id
, name
, city
FROM customers;6. Say the join type, and use ON
A comma between tables with the match in WHERE is an old style. It hides the join among the filters, and if you forget the WHERE line you get every row times every row. Write INNER JOIN or LEFT JOIN, with ON.
BAD
Show the result without running
| name | match_date | home_goals | away_goals |
|---|---|---|---|
| Riverside Rovers | 2024-08-03 | 2 | 2 |
| Northside Wanderers | 2024-08-17 | 1 | 2 |
| Northside Wanderers | 2024-08-17 | 0 | 1 |
| Northside Wanderers | 2024-08-24 | 1 | 0 |
| Riverside Rovers | 2024-08-31 | 2 | 1 |
| Riverside Rovers | 2024-09-07 | 1 | 1 |
| Riverside Rovers | 2024-09-14 | 2 | 1 |
GOOD
Show the result without running
| name | match_date | home_goals | away_goals |
|---|---|---|---|
| Riverside Rovers | 2024-08-03 | 2 | 2 |
| Northside Wanderers | 2024-08-17 | 1 | 2 |
| Northside Wanderers | 2024-08-17 | 0 | 1 |
| Northside Wanderers | 2024-08-24 | 1 | 0 |
| Riverside Rovers | 2024-08-31 | 2 | 1 |
| Riverside Rovers | 2024-09-07 | 1 | 1 |
| Riverside Rovers | 2024-09-14 | 2 | 1 |
Same result both ways: 7 rows, 4 columns.
Plain JOIN means INNER JOIN. Writing INNER tells the reader you chose it, not that you forgot about LEFT.
7. Comment the purpose and the grain
One line on what question the query answers. One line on what a row of the result means. A short grain comment on each CTE. Do not comment what the code already says: -- select the name wastes a line.
BAD
Show the result without running
| name | n |
|---|---|
| Larkspur Freight | 2 |
| Willowby Insurance | 2 |
| Kettlebrook Bank | 1 |
| Pixelmoor Games | 1 |
GOOD
Show the result without running
| name | declined_offers |
|---|---|
| Larkspur Freight | 2 |
| Willowby Insurance | 2 |
| Kettlebrook Bank | 1 |
| Pixelmoor Games | 1 |
Same result both ways: 4 rows, 2 columns.
8. No SELECT * in the final output
SELECT * is fine while you explore and inside a quick check. In anything you hand over, list the columns. The reader sees exactly what comes back, and a new column added to the table later does not sneak into your report.
BAD
Show the result without running
| offer_id | company_id | job_family | level | base_salary | offered_at | accepted_at | status |
|---|---|---|---|---|---|---|---|
| 3 | 10 | Product | Mid | 61000 | 2023-01-16 | NULL | pending |
GOOD
Show the result without running
| offer_id | company_id | job_family | level | base_salary | offered_at |
|---|---|---|---|---|---|
| 3 | 10 | Product | Mid | 61000 | 2023-01-16 |
Not the same columns on purpose: the good one drops accepted_at and status, which tell you nothing for a pending offer.
9. No magic numbers
A bare 30 or 0.15 in the middle of a query is a question the reader has to answer. Name it. In SQL, a one-row params CTE at the top does the job; in Hex, an input parameter does.
BAD
Show the result without running
| listener_id | plays |
|---|---|
| 6 | 27 |
| 1 | 17 |
| 11 | 17 |
| 3 | 16 |
| 12 | 16 |
GOOD
Show the result without running
| listener_id | plays |
|---|---|
| 6 | 27 |
| 1 | 17 |
| 11 | 17 |
| 3 | 16 |
| 12 | 16 |
Same result both ways: 5 rows, 2 columns.
Longer, yes. But the rules are in one place, with names, and changing 30 to 60 is a one-line edit. For a short exam answer, a comment next to the number is a fair middle ground.
10. Qualify every column once there is a join
When two tables are in play, write o.customer_id, not customer_id. If the column is only in one table it still runs, but the reader has to check which. If it is in both, the query fails, or worse, picks the one you did not mean.
BAD
Show the result without running
| name | order_date | quantity |
|---|---|---|
| Eoin Murphy | 2025-01-29 | 1 |
| Aoife Byrne | 2025-02-05 | 1 |
| Ciara Brennan | 2025-02-07 | 1 |
| Oisin Ryan | 2025-04-01 | 1 |
| Fionn Daly | 2025-04-03 | 1 |
| Sinead Moran | 2025-04-14 | 1 |
| Grainne Lynch | 2025-06-01 | 2 |
| Ciara Brennan | 2025-06-11 | 1 |
GOOD
Show the result without running
| name | order_date | quantity |
|---|---|---|
| Eoin Murphy | 2025-01-29 | 1 |
| Aoife Byrne | 2025-02-05 | 1 |
| Ciara Brennan | 2025-02-07 | 1 |
| Oisin Ryan | 2025-04-01 | 1 |
| Fionn Daly | 2025-04-03 | 1 |
| Sinead Moran | 2025-04-14 | 1 |
| Grainne Lynch | 2025-06-01 | 2 |
| Ciara Brennan | 2025-06-11 | 1 |
Same result both ways: 8 rows, 3 columns.
Which table has name? Products has one too. Join products in later and the bad version breaks with ambiguous column name.
Order of the final query, for reference: purpose comment, params, cleaning steps, aggregate steps, final SELECT with listed columns, ORDER BY. CTEs: write SQL in steps covers how to build and test the steps.
3 Python style
The examples use pandas on the same made-up offers table (offer_id, company_id, job_family, level, base_salary, offered_at, accepted_at, status). Assume it is already loaded. Each BAD and GOOD pair was run and gives the same result, except rule 6, where the bad version is broken on purpose.
1. Names that say what they hold
df2, x, temp tell the reader nothing. A name should answer what is in here. Use snake_case. Plural for collections.
BAD
d = offers[offers["status"] == "accepted"]
x = d.groupby("job_family")["base_salary"].mean()
x2 = x[x > 50000]GOOD
accepted = offers[offers["status"] == "accepted"]
avg_salary_by_family = accepted.groupby("job_family")["base_salary"].mean()
well_paid_families = avg_salary_by_family[avg_salary_by_family > 50000]2. Constants at the top, in capitals
Thresholds, file names and dates belong in one place at the top, named in CAPITALS so everyone knows not to change them halfway down.
BAD
recent = offers[offers["offered_at"] >= "2024-01-01"]
senior = recent[recent["base_salary"] >= 60000]
print(len(senior))GOOD
START_DATE = "2024-01-01" # the period the question asks about
HIGH_SALARY = 60_000 # threshold from the brief
recent = offers[offers["offered_at"] >= START_DATE]
high_paid = recent[recent["base_salary"] >= HIGH_SALARY]
print(len(high_paid))60_000 is the same number as 60000. The underscore is only there to help you read it.
3. Small functions with one job, a docstring and light type hints
If you can describe a block of code as clean the offers or median salary per family, it wants to be a function with that name. A one-line docstring says what it returns. Type hints on the arguments and return value are enough; you do not need them on every variable.
BAD
o = offers.drop_duplicates(subset=["company_id", "job_family", "level", "base_salary", "offered_at"])
o = o.dropna(subset=["base_salary"])
o = o[o["status"] == "accepted"]
result = o.groupby("job_family")["base_salary"].median()GOOD
DUPLICATE_KEY = ["company_id", "job_family", "level", "base_salary", "offered_at"]
def clean_offers(offers: pd.DataFrame) -> pd.DataFrame:
"""Drop duplicate offers and offers with no salary."""
return (
offers
.drop_duplicates(subset=DUPLICATE_KEY)
.dropna(subset=["base_salary"])
)
def median_salary_by_family(offers: pd.DataFrame) -> pd.Series:
"""Median accepted salary for each job family."""
accepted = offers[offers["status"] == "accepted"]
return accepted.groupby("job_family")["base_salary"].median()
result = median_salary_by_family(clean_offers(offers))Longer, and better. Each function can be tested alone, and the last line reads like the question.
4. No copy-paste blocks
When you see the same three lines three times with one word changed, write it once and loop, or let groupby do it. Copies drift: you fix a bug in one and not the others.
BAD
data = offers[offers["job_family"] == "Data"]
data_avg = data["base_salary"].mean()
design = offers[offers["job_family"] == "Design"]
design_avg = design["base_salary"].mean()
product = offers[offers["job_family"] == "Product"]
product_avg = product["base_salary"].mean()
avgs = {"Data": data_avg, "Design": design_avg, "Product": product_avg}GOOD
FAMILIES = ["Data", "Design", "Product"]
avgs = (
offers[offers["job_family"].isin(FAMILIES)]
.groupby("job_family")["base_salary"]
.mean()
.to_dict()
)5. f-strings for text
Gluing strings together with + and str() is hard to read and easy to break. An f-string shows the sentence as it will print. The part after the colon formats the number.
BAD
for family, avg in offers.groupby("job_family")["base_salary"].mean().items():
print("Average for " + family + ": " + str(int(round(avg))))GOOD
avg_by_family = offers.groupby("job_family")["base_salary"].mean()
for family, avg in avg_by_family.items():
print(f"Average for {family}: {avg:.0f}")Want commas in big numbers? {avg:,.0f} prints 52,333.
6. Set values with .loc, never with chained brackets
df[mask]["col"] = value picks rows, makes a copy, then sets the value on the copy. Your table does not change. Older pandas warns; pandas 3 never changes the original. Use .loc[rows, column] in one go, or build the whole column at once.
BAD: changes nothing
offers["band"] = "standard"
offers[offers["base_salary"] >= 60000]["band"] = "high"
high_count = (offers["band"] == "high").sum()GOOD
offers["band"] = "standard"
offers.loc[offers["base_salary"] >= 60000, "band"] = "high"
high_count = (offers["band"] == "high").sum()The bad version runs with no error and high_count is 0. That is why it is dangerous. The same trap hits accepted = offers[mask] followed by accepted["x"] = ...: add .copy() when you take a slice you plan to change.
7. Method chains: one step per line
A chain in brackets, one method per line, reads like the CTE steps in SQL. Four throwaway names (df2 to df5) become one good one.
BAD
df2 = offers[offers["status"] == "accepted"]
df3 = df2.dropna(subset=["base_salary"])
df4 = df3.groupby("level", as_index=False)["base_salary"].median()
df5 = df4.sort_values("base_salary", ascending=False)GOOD
median_by_level = (
offers
.query("status == 'accepted'")
.dropna(subset=["base_salary"])
.groupby("level", as_index=False)["base_salary"]
.median()
.sort_values("base_salary", ascending=False)
)Keep chains to about six steps. Longer than that, split at a point you can name.
8. Asserts as sanity checks
An assert stops the notebook with a message if something you believe is not true. Put them after loading and after every join. They are the Python version of the row-count checks in the CTE guide.
merged = offers.merge(companies, on="company_id", how="left")
assert offers["offer_id"].is_unique, "offer_id should be unique"
assert len(merged) == len(offers), "the join changed the row count"
assert merged["name"].notna().all(), "an offer has no matching company"
assert offers["base_salary"].dropna().between(10_000, 500_000).all(), "salary out of range"
If an assert fails in a take-home, do not delete it. Write a comment on what you found and how you handled it. That is the kind of thing a reviewer is looking for.
9. PEP 8 basics
PEP 8 is the style guide most Python follows. Read it here. You do not need to learn it all. These cover most of what a reviewer notices:
- Four spaces per indent. No tabs.
snake_casefor variables and functions,CAPITALSfor constants,CamelCasefor classes.- Imports at the top, one per line.
- Spaces around
=and operators:total = price * qty. No spaces around=in keyword arguments:dropna(subset=["x"]). - Two blank lines before each top-level function.
- Keep lines short enough to read without scrolling. PEP 8 says 79 characters; many teams allow up to about 100.
A formatter such as black or ruff format fixes most of this for you. Many teams run one on every save.
4 Notebooks and Hex: lay it out for the reader
A notebook is read top to bottom by someone who did not watch you build it. Lay it out in the order they need, not the order you worked in.
The order you worked in
- Codeimport pandas as pd
- Codedf = pd.read_csv(...)
- Codedf.head()
- Codedf2 = df[df.x > 0]
- Codedf.describe() # old, unused
- Codeimport matplotlib...
- Codeplt.plot(...) # no title
- Codedf3 = ... # does it still run?
- Textsome results: 52k
The order a reader needs
- TextTitle and question. What are we answering, for whom, and when the data was pulled.
- TextFindings. Three bullets with the numbers. Written last, placed first.
- TextAssumptions. How you handled duplicates, missing values, dates and ties.
- CodeSetup. Imports and constants.
- CodeLoad. Read the data. Nothing else.
- CodeCheck. Shape, types, missing values, duplicates, asserts.
- CodeClean. One function or one chain, named.
- CodeAnalyse. One question per cell, with a markdown line above it.
- CodeChart. Title that states the finding, labelled axes.
- TextLimits and next steps. What you would check with more time.
Rules for any notebook
- Findings at the top. A reviewer with ten minutes reads the top cell and the chart. Make sure those two tell the story.
- One idea per cell. If a cell loads, cleans and charts, nobody can rerun just the part that changed.
- Name outputs clearly.
accepted_offers,median_by_level. Neverdf5. - Delete dead cells. Old experiments,
df.head()left everywhere, a cell that errors. If you want to keep an experiment, move it to an appendix at the bottom with a heading. - Restart and run all before you share. In Jupyter: Kernel, then Restart & Run All. Notebooks keep variables from cells you have since deleted or changed, so a notebook can look fine and still fail from the top. This catches it.
- Charts state the finding. Data offers pay the most at every level beats Salary by family.
Hex in particular
- Name every cell and every output. A SQL cell's result is a dataframe the next cell can use.
accepted_offersis clear;dataframe_3is not. - Hex runs cells by what they depend on. Change a cell and Hex reruns the cells that use its result. The page order and the run order can differ. Keep them the same on purpose, so the logic reads top to bottom, and use Run all before you share.
- Use input parameters for thresholds. A number input or dropdown is Hex's version of a named constant, and the reviewer can change it.
- Chain SQL cells while you work, then fold them. For an exam answer, one CTE query is easier to grade. The CTE guide shows how to fold cells into one query.
- Build the app view for the reader. Put the question, findings, the key chart and the assumptions in the app. Leave the working in the logic view.
A good check cell
# Check: what did we load?
print(f"{len(offers)} offers, {offers['offer_id'].nunique()} unique IDs")
print(offers.isna().sum().loc[lambda s: s > 0])
print(offers["status"].value_counts())
dupes = offers.duplicated(subset=["company_id", "job_family", "level", "base_salary", "offered_at"])
print(f"{dupes.sum()} exact duplicate offer(s)")
On the practice data this prints 45 offers, missing values in base_salary and accepted_at, and one duplicate. Each line becomes a sentence in the Assumptions cell.
5 Refactor this
Three pieces of working but messy code. Rewrite each one, then open the model answer. Yours does not have to match it word for word; it should be just as easy to check.
Shop Exercise 1: SQL
This runs and gives the right answer. Rewrite it in the box using the ten rules, and press Check: your version must still give the same result. Check compares values, not column names, so name them well.
Refactor the query below without changing its result.
Hint
Start with the comma joins: turn them into INNER JOINs with ON. Then name the count and the sum, give the aliases meaning, and lift the price filter into a step.
The original (for comparison)
Model clean version
Show the result without running
| name | orders | net_spend |
|---|---|---|
| Ciara Brennan | 3 | 172.5 |
| Aoife Byrne | 4 | 167.99 |
| Saoirse Doyle | 3 | 163.5 |
| Cian Walsh | 3 | 122.0 |
| Sinead Moran | 4 | -309.0 |
| Orla Kavanagh | 3 | -528.5 |
| Tadhg Burke | 3 | -560.0 |
| Fionn Daly | 3 | -702.0 |
| Niamh Kelly | 4 | -1216.0 |
| Roisin Quinn | 3 | -1359.51 |
Same result as the original, row for row.
The planted wrong answer most people hit: dropping the COALESCE while tidying. Orders with no discount then give NULL, and SUM skips them. Tidying must not change logic.
Jobs Exercise 2: Python
Median accepted salary by level for offers made in 2024. Copy it into a notebook and tidy it. Look for: names, a constant, copy-paste, string gluing, and a function waiting to get out.
import pandas as pd
df = pd.read_csv("offers.csv")
df2 = df[df['status']=='accepted']
df2 = df2.dropna(subset=['base_salary'])
df3 = df2[df2['offered_at']>='2024-01-01']
a=df3[df3['level']=='Junior']['base_salary'].median()
b=df3[df3['level']=='Mid']['base_salary'].median()
c=df3[df3['level']=='Senior']['base_salary'].median()
print('Junior: '+str(a))
print('Mid: '+str(b))
print('Senior: '+str(c))
Model clean version
import pandas as pd
OFFERS_FILE = "offers.csv"
START_DATE = "2024-01-01" # the question asks about 2024 offers
LEVELS = ["Junior", "Mid", "Senior"]
def accepted_offers_since(offers: pd.DataFrame, start: str) -> pd.DataFrame:
"""Accepted offers with a salary, made on or after start."""
return offers[
(offers["status"] == "accepted")
& offers["base_salary"].notna()
& (offers["offered_at"] >= start)
]
offers = pd.read_csv(OFFERS_FILE)
recent = accepted_offers_since(offers, START_DATE)
median_by_level = recent.groupby("level")["base_salary"].median()
for level in LEVELS:
print(f"{level}: {median_by_level[level]}")Both print the same three lines:
Junior: 42000.0
Mid: 55750.0
Senior: 71250.0App Exercise 3: a notebook
A take-home asked: which signup channel brings the users most likely to subscribe? Here are the cells as submitted, in order. Put them in the order a reviewer needs, and say which to cut.
- Codeimport pandas as pd, matplotlib.pyplot as plt
- Codeevents = pd.read_csv('events.csv')
- Codeevents.head()
- Codeusers = pd.read_csv('app_users.csv')
- Codeusers.head()
- Codem = users.merge(events) # rows went up?
- Codeplt.bar(...) # chart, no title
- Codesubs = events[events.event_name == 'subscribe']
- TextFriend referrals convert best
- Code# old attempt, errors: KeyError
- Coderate = subs.groupby(...)...
Model order
- Text: the question, and a one-line answer: which referrer converts best, with the rate.
- Text: assumptions. Users with no referrer grouped as none. Counted people, not events (one event is logged twice).
- Code: imports and constants.
- Code: load both files.
- Code: check: row counts, missing referrers, duplicate events, with asserts.
- Code: one row per user with a subscribed flag. Assert the row count equals the number of users.
- Code: subscribe rate per referrer.
- Code: chart with a title that states the finding.
- Text: limits: small numbers per group, so treat differences with care.
Cut: both .head() cells, the old cell that errors, and the merge that multiplies rows (replace it with the one-row-per-user step). Fix: the findings cell moves to the top and says the rate, not just the winner.
The reviewer's scorecard
This is roughly what a reviewer runs through. Score your own work before you send it. Tick what is true.
0 of 12. Ten or more and a reviewer can trust your work quickly.
6 The one-page checklist
Print it, or keep it open next to your next take-home.
Code your teammates can follow: checklist
SQL
- Purpose and grain comment at the top
- One clause per line, one keyword case
- CTEs named for what they hold, grain comment on each
- Aliases that mean something, with AS
- INNER or LEFT JOIN with ON, never commas
- Every column qualified once there is a join
- Thresholds named in a params step or commented
- Columns listed in the final SELECT
- Row counts checked after each join
Python
- Names that say what they hold, snake_case
- Constants at the top in CAPITALS
- Small functions, one job, docstring, type hints
- No copy-paste: loop or groupby
- f-strings for text
- .loc to set values, .copy() on slices you change
- Method chains, one step per line
- Asserts after loading and after joins
- Formatter run (black or ruff)
Notebook or Hex
- Title and question at the top
- Findings next, with numbers
- Assumptions written down
- Load, check, clean, analyse, chart
- One idea per cell, outputs named
- Dead cells deleted
- Charts titled with the finding
- Restart and run all (Hex: Run all)
- Read it once as the reviewer
davidcarr.me/guides/readable-code
▸ Where next
- CTEs: write SQL in stepsBuild, check and test queries one named step at a time.
- A take-home, walked throughSee these habits used on a full task.
- SQL by example28 patterns to practise on.
- Python by exampleThe same patterns in pandas.
- SQL from zeroEvery idea explained slowly.
- Data tech examsWhat the timed tests look like.