Every exercise in 00_start.py, with the solution and why it works. Each answer stays closed until you swear you tried it first. Opening one changes nothing in your notebook; your check still has to go green from your own code. Read the whole notebook, with its lessons.
Exercise 1.1. The codes of a variable
The task
Why it matters: a codebook writes its codes as text, such as 1 = Male; 2 = Female; 9 = Not stated. Turned into a dictionary, they can label a table or a chart, and tell you which values to treat as missing.
Input → output: the values text of one codebook row → a dictionary of each code and what it means.
values |
returns |
|---|---|
"1 = Male; 2 = Female; 9 = Not stated" |
{"1": "Male", "2": "Female", "9": "Not stated"} |
"999 = Not stated" |
{"999": "Not stated"} |
"Rice; Corn; Vegetables; Banana; blank = not recorded" |
{"blank": "not recorded"} |
'' (empty: a variable with no codes) |
{} |
The parts are separated by "; " (a semicolon and a space). A part written code = meaning becomes one entry; a part without " = ", such as Rice, is a value that means itself, and is left out. The codes stay text, as written: "1", not 1.
Tools (Python Essentials, modules 3 to 6): text.split("; ") gives the list of parts; " = " in part is True when the part holds =; part.split(" = ", 1) splits at the first = only, into two pieces, and code, meaning = ... names them; meanings[code] = meaning stores an entry in a dictionary.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| ValueError: too many values to unpack (expected 2, got 3) | The part sqm = square meters (1 ha = 10,000 sqm) holds two =; splitting at both gives three pieces for two names. |
part.split(" = ", 1): split at the first only |
| ValueError: not enough values to unpack (expected 2, got 1) | A part without =, such as Rice, was split too. |
if " = " in part: before splitting |
Codes such as " 2", with a space in front |
The text was split at ";" without its space. |
values.split("; ") |
| Only the first code comes back | return is inside the loop, so the function ends after the first part. |
move return meanings out of the loop, to the function's own indentation |
None |
The function has no return, or prints the dictionary instead. |
end with return meanings |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Split the text into its parts, keep the parts written code = meaning, and split each of those once, at its first =, into a dictionary entry.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def code_meanings(values: str) -> dict: """The codes written in a codebook's `values` text, each with what it means.""" # Exercise 1.1: the task and examples are in the text above this cell. meanings = {} for part in values.split("; "): if " = " in part: code, meaning = part.split(" = ", 1) meanings[code] = meaning return meaningsWhy each part is there
values.split("; ")gives the parts. Splitting at";"alone would leave a space in front of every code after the first, so" 2"would not equal"2".if " = " in partskips the values that mean themselves (Rice,Yes). Without it,code, meaning = part.split(" = ", 1)raises ValueError: not enough values to unpack (expected 2, got 1) onRice, because there is nothing to split.- The
1inpart.split(" = ", 1)splits at the first=only. The area unit's text,sqm = square meters (1 ha = 10,000 sqm), holds a second=; split at both, it gives three pieces, and naming themcode, meaningraises ValueError: too many values to unpack (expected 2, got 3). - The codes are kept as the text they are:
"9", not9. Codes are labels, and some, such asha, are not numbers at all. - An empty
valuesgives[""]when split: one part without=, so the dictionary stays empty,{}, with noifneeded for it.
Exercise 1.2. Is it a PSGC code?
The task
Why it matters: a code that went through a number column or was typed by hand comes back damaged in ways that are easy to miss: its leading zero lost, .0 added when a number was turned back into text, a space at the end, the letter O typed for a zero. A test that a code is still 10 digits catches all of them, before the code is used to join or group.
Input → output: a code, as text → True when it is exactly 10 characters, every one a digit; False otherwise.
code |
returns | why |
|---|---|---|
"0102820000" |
True |
10 digits |
"102820000" |
False |
9 digits: the leading zero was lost |
"O102820000" |
False |
10 characters, but the first is the letter O, not a zero |
Tools (Python Essentials, modules 2 and 6): len(code) is the number of characters; code.isdigit() is True when every character is a digit; and is True only when both sides are.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
True for 'O102820000' |
Only the length is tested. | add code.isdigit() |
True for '102820000' |
Only the digits are tested. | add len(code) == 10 |
True for '0102820000 ' |
The space was removed before testing. The task asks about the code as it is. | test code itself, without .strip() |
False for '1204701000' |
The code is tested for a leading 0. Codes from Region X onward start with 1. |
test the length and the digits, not the first character |
| TypeError: object of type 'int' has no len() | Your own test gave the function a number; codes are text, and the check gives text only. | call it with text: is_psgc_code("0102820000") |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A PSGC code is two facts at once: exactly 10 characters, and every character a digit. Test both, and return True only when both hold.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def is_psgc_code(code: str) -> bool: """Whether a code is exactly 10 characters, all digits, as a PSGC code is.""" # Exercise 1.2: the task and examples are in the text above this cell. return len(code) == 10 and code.isdigit()Why each part is there
len(code) == 10catches a code that lost its leading zero ("102820000", 9 characters) or gained something ("0102820000 "and"102820000.0", 11).code.isdigit()catches a code of the right length that is not all digits, such as"O102820000", with the letter O for a zero, which is exactly 10 characters.- Neither test alone is enough, which is why the check has a case for each:
"102820000"is all digits, and"O102820000"is 10 characters.andjoins them. - The expression is already
TrueorFalse, so it can be returned as it is, without anif. - An empty text is 0 characters, and
"".isdigit()isFalse: it fails both tests, with nothing special to write for it.
Exercise 1.3. Households represented
The task
Why it matters: "how many farm households are there in this province?" is a sum of weights, not a count of interviews. Counting the rows answers a different question: how many were interviewed.
Input → output: a list of households, each a dictionary with at least "province" and "weight", and a province's name → the sum of the weights of that province's households, rounded to a whole number; 0 when none is in that province.
records = [
{"hh_id": "A", "province": "Iloilo", "weight": 250.4},
{"hh_id": "B", "province": "Iloilo", "weight": 310.2},
{"hh_id": "C", "province": "Bukidnon", "weight": 512.75},
{"hh_id": "D", "province": "Iloilo", "weight": 99.1},
]
households_represented(records, "Iloilo") # 660: 250.4 + 310.2 + 99.1 is 659.7, rounded
households_represented(records, "Cotabato") # 0
Tools (Python Essentials, modules 3 to 5): a total that starts at 0; for record in records:; if record["province"] == province:; round(value), which rounds to the nearest whole number.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
3 for Iloilo in the four households |
The function counts the households instead of adding their weights. | total = total + record["weight"] |
659.7 for Iloilo |
The total is not rounded. | return round(total) |
659 for Iloilo |
int(...) cuts the decimals off instead of rounding. |
round(total) |
250 for Iloilo |
return is inside the loop, so the function stops at the first household. |
return at the function's own indentation, after the loop |
| The same total for every province | The if is missing, so every household is added. |
if record["province"] == province: |
| KeyError: 'Weight' | The key is spelled differently from the dictionaries'. Keys are exact, lower case included. | record["weight"], record["province"] |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Each household stands for as many farm households as its weight, so the province's farm households are the sum of its households' weights: add up the weights of the records in that province, then round.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def households_represented(records: list[dict], province: str) -> int: """How many farm households a province's interviewed households stand for: the sum of their weights, rounded.""" # Exercise 1.3: the task and examples are in the text above this cell. total = 0 for record in records: if record["province"] == province: total = total + record["weight"] return round(total)Why each part is there
- The total starts at
0before the loop, so a province with no households gives0, as the task asks, with no special case. if record["province"] == provincekeeps only that province's households; the weight is added inside theif.- It adds
record["weight"], not1: adding 1 per record counts the interviews, which is 3 for Iloilo in the example, not 660. round(total)comes once, after the loop.roundgoes to the nearest whole number, so 659.7 becomes 660;int(659.7)would cut the decimals and give 659.returnis after the loop, at the function's own indentation; inside the loop it would end the function at the first record.
Exercise 1.4. Plots by crop, in the library of your choice
The task
Why it matters: each library asks for the same chart in its own terms. Drawing one yourself, from a table you have not charted yet, is how you learn which terms.
Input → output: a table with a crop column and a plots column → a bar chart with one bar per crop, as long as its number of plots. Return the chart: the axes for matplotlib or seaborn, the Chart for Altair.
| crop | plots |
|---|---|
| Rice | 12 |
| Corn | 5 |
gives two bars, Rice 12 long and Corn 5. The survey's own table is under this text; the Try it cell charts it.
Use any one of the three libraries: the check compares the bars drawn (each bar's crop and its length), not the picture, so titles, colors and whether the bars run up or across are yours to choose.
Tools: the three functions above. In matplotlib, ax.bar(x values, heights) draws upright bars and ax.barh(...) bars across; in seaborn, sns.barplot(data=table, x=..., y=..., errorbar=None, ax=ax); in Altair, alt.Chart(table).mark_bar().encode(x=..., y=...). For matplotlib and seaborn, make a fresh figure inside the function: fig, ax = plt.subplots().
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| TypeError: chart_data reads a matplotlib, seaborn or Altair chart, not a builtins.NoneType | The function draws the chart but does not return it. | the last line: return ax (matplotlib, seaborn), return the Chart (Altair) |
| Some tables are right, others show extra bars | The bars were drawn on a chart already there (seaborn without ax=, or plt.bar), so each table's bars pile onto the ones before. |
fig, ax = plt.subplots() inside the function, and ax=ax for seaborn |
| Every bar is 1 long | The chart counts the rows (seaborn's countplot, Altair's count()) instead of drawing the plots column. |
ax.bar(table["crop"], table["plots"]), or y="plots" |
KeyError: 'Crop' (matplotlib), Could not interpret value Crop (seaborn) or Unable to determine data type for the field "Crop" (Altair) |
A column name that is not in the table. Names are exact, lower case included. | the columns: crop and plots |
| Right for the survey's table, wrong for the small ones | The function charts plots_per_crop instead of its input. |
use table everywhere inside the function |
0 of 3 tables are right, and the chart shows a line |
A line chart (ax.plot, sns.lineplot, mark_line): the check reads bars. |
ax.bar, sns.barplot, mark_bar |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A bar per crop, as long as its plots: in matplotlib that is a fresh figure and axes and one ax.bar call with the two columns' values; seaborn and Altair would take the table and the two column names instead. Any of the three passes.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def crop_chart(table: pd.DataFrame): """A bar chart of the number of plots of each crop.""" # Exercise 1.4: the task and examples are in the text above this cell. fig, ax = plt.subplots(figsize=(6, 3)) ax.bar(table["crop"], table["plots"]) ax.set_ylabel("plots") ax.set_title("Plots by crop") return axWhy each part is there
fig, ax = plt.subplots()makes a new figure for every call. The check calls the function once per test table; drawing on one figure for all of them would pile the second table's bars on the first's.ax.bar(table["crop"], table["plots"])gives matplotlib the values themselves: the crops for the bars' places, the plots for their heights. It draws from the inputtable, so it works for any table with these two columns.- The labels and title are for readers; the check reads only the bars, so they never change its result.
return axhands the chart back. Without it the function returnsNone: marimo has nothing to show, and the check says chart_data reads a matplotlib, seaborn or Altair chart, not a builtins.NoneType.- In seaborn:
fig, ax = plt.subplots(), thensns.barplot(data=table, x="crop", y="plots", errorbar=None, ax=ax)andreturn ax. In Altair:return alt.Chart(table).mark_bar().encode(x="crop", y="plots"). Both draw the same bars, so both pass the same check.
Exercise 1.5. Any column, by province
The task
Why it matters: a chart function that takes the column to draw as an input works for every column of the table. It is also where a common slip shows: the input column holds a column's name, so it is written without quotes.
Input → output: a table with a province column, and the name of another of its columns → a bar chart with one bar per province, as long as that column's value.
| call | draws |
|---|---|
province_chart(by_province, "farm_households") |
the chart above, in any library |
province_chart(by_province, "interviewed") |
seven bars, all 170 long |
Tools: as in Exercise 1.4. Where the examples write "farm_households", write column: table[column] in matplotlib, x=column in seaborn and Altair.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| KeyError: 'column' | The input's name is written in quotes, table["column"], so pandas looks for a column called column. |
table[column], without quotes |
Could not interpret value column (seaborn) or Unable to determine data type for the field "column" (Altair) |
The same, in seaborn or Altair: x="column". |
x=column |
Right for farm_households, wrong for interviewed |
The function still names the example's column instead of using its input. | every place a column is named, except "province" |
Right for by_province, wrong for the two-province table |
The function charts by_province instead of its input. |
use table everywhere inside the function |
| Some cases are right, others show extra bars | The bars pile onto a chart already there. | fig, ax = plt.subplots() inside the function, and ax=ax for seaborn |
| TypeError: chart_data reads … not a builtins.NoneType | No return. |
return ax, or return the Chart |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
The section's chart with the column's name taken from the input: in Altair, the bar mark with column on one axis and the provinces on the other. matplotlib or seaborn would pass the same check.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def province_chart(table: pd.DataFrame, column: str): """A bar chart of one column of the table, a bar per province.""" # Exercise 1.5: the task and examples are in the text above this cell. return alt.Chart(table).mark_bar().encode(x=column, y="province")Why each part is there
x=columnuses the input, which holds a name such as"interviewed". Writtenx="column", Altair looks for a column called column and raises Unable to determine data type for the field "column"; seaborn raises Could not interpret valuecolumnforx, and matplotlib'stable["column"]raises KeyError: 'column'.y="province"stays a name in quotes: it is the same column in every call.- Which axis is which does not matter to the check: a bar is read as its province and its length, whether the bars run across (as here) or up.
- The chart is returned as built; Altair draws nothing until marimo shows it, and the check reads the data behind it.
- In matplotlib:
fig, ax = plt.subplots(),ax.barh(table["province"], table[column]),return ax. In seaborn:fig, ax = plt.subplots(),sns.barplot(data=table, x=column, y="province", errorbar=None, ax=ax),return ax.