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.
Warm-up. Your first function
The task
Task. Finish double(n) so that it returns the number n times two (* multiplies).
| call | returns |
|---|---|
double(21) |
42 |
double(0) |
0 |
If the check is red
Use return, not print.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A function hands its result back with return. Here the result is n times two, so the whole function is one line.
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 double(n): return n * 2Why each part is there
return n * 2works outn * 2and gives that value to whoever calleddouble. The check callsdouble(21)and compares what comes back with42; it never looks at the screen.- The tempting version is
print(n * 2). It shows42on the screen, but the function then gives back nothing (None), so the check seesNonefor every input and stays red. - Nothing else is needed: no variable to keep the result first, and no
iffor zero or negative numbers, because*already handles them (double(-3)gives-6).
Your turn 4.1. Pad a code
The task
Task. Finish pad_code(code, width): return the text code, padded on the left with zeros until it is width characters long.
| call | returns |
|---|---|
pad_code("128", 4) |
"0128" |
pad_code("7", 3) |
"007" |
If the check is red
Look at what .zfill does with a code that is already long enough.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
.zfill(width) already does the whole job: it adds zeros on the left until the text is width characters long. The function only has to hand back what it gives.
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 pad_code(code, width): return code.zfill(width)Why each part is there
code.zfill(width)works becausecodeis text. A number has no.zfill, which is one more reason codes stay text..zfillnever shortens and never adds to a code that is long enough already:pad_code("40500", 10)gives"0000040500", butpad_code("0012", 4)andpad_code("99", 2)come back unchanged. That is what the check's hint points at: noifis needed for those.- The width comes from the input, never a fixed
4:pad_code("1", 6)must give"000001".
Your turn 4.2. Codes that are not on the list
The task
Task. Finish codes_not_listed(round_codes, listed_codes): return the set of codes that are in round_codes but not in listed_codes.
| call | returns |
|---|---|
codes_not_listed({"01", "02", "99"}, {"01", "02", "03"}) |
{"99"} |
codes_not_listed({"01"}, {"01", "02"}) |
set() (an empty set) |
If the check is red
Look at the four operations in the explainer above.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Both inputs are sets, and "in the first but not in the second" is exactly what subtracting one set from another means.
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 codes_not_listed(round_codes, listed_codes): return round_codes - listed_codesWhy each part is there
round_codes - listed_codeskeeps every code ofround_codesthatlisted_codesdoes not have. The order matters:listed_codes - round_codesanswers the other question, the codes on the list that the round never used.- The result is a set, so it can be empty: when every code is listed, the answer is
set(), and the check expects exactly that, notNoneand not an empty list. - A loop that tests each code with
if code not in listed_codesgives the same answer, in five lines instead of one; the set operator is what these questions are for.
Your turn 4.3. Write a SELECT
The task
Task. Finish select_sql(columns, table): return the SQL text that selects the columns from table.
| call | returns |
|---|---|
select_sql(["hhid", "age"], "round1") |
"SELECT hhid, age FROM round1" |
select_sql(["weight"], "people") |
"SELECT weight FROM people" |
If the check is red
Check the spaces: a comma and one space between columns, one space around SELECT and FROM.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
SQL is text, so building a query is building a string: the column names joined with commas, placed between SELECT and FROM.
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 select_sql(columns, table): return f"SELECT {', '.join(columns)} FROM {table}"Why each part is there
', '.join(columns)glues the list into one text with a comma and a space between names:['hhid', 'age']becomes'hhid, age'. With one column,['age'], there is nothing to put between, so no stray comma.- The f-string
f"SELECT {...} FROM {table}"places that text and the table name with exactly one space aroundSELECTandFROM. The check compares the text character by character, so a missing or extra space, or','without its space, turns it red. - Writing
str(columns)instead of joining gives"['hhid', 'age']", brackets and quotes included, which is Python's way of showing a list, not SQL.
Your turn 4.4. The region of an area code
The task
Task. Finish region_of(area_code, width=2): return the first width characters of area_code. With the default width (2), that is the region.
| call | returns |
|---|---|
region_of("0100305000") |
"01" |
region_of("0100305000", 5) |
"01003" |
If the check is red
Use the input width in your slice, not a fixed number.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
An area code's first characters are its region, so the answer is a slice: the first width characters of the text.
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 region_of(area_code, width=2): return area_code[:width]Why each part is there
area_code[:width]is "from the start, up to but not including positionwidth":'0100305000'[:2]is'01', and[:5]is'01003'.widthcomes from the input, and its default of 2 is in the function's first line (width=2), soregion_of('0100305000')gives the region without being told. A fixed[:2]failsregion_of('1234', 3), which must give'123'.- Slicing works because the code is text. Had the zero been lost to a number,
0100305000would be100305000, and its first two characters would be'10', the wrong region.
Your turn 4.5. Missing or empty
The task
Task. Finish count_missing_or_empty(values): values is a Series; return how many of its values are missing or are the empty text '', as a whole number.
| values | returns |
|---|---|
pd.Series(['01', None, '', '02']) |
2 |
pd.Series(['01', '02']) |
0 |
If the check is red
Count both kinds: missing values and empty texts.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Two kinds of "nothing" sit in a column: a missing value and an empty text. Build one True or False per value for each kind, combine them with "or", and count the Trues.
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 count_missing_or_empty(values): return int((values.isna() | values.eq("")).sum())Why each part is there
values.isna()isTruewhere a value is missing (NoneorNaN);values.eq("")isTruewhere it is the empty text. Neither alone is enough: a missing value is not equal to"", and""is not missing.|combines the two, value by value:Truewhen either is. Python'sordoes not work here, because it compares whole Series, not their values one by one..sum()counts the Trues (each counts as 1), andint(...)turns pandas' own number type into a plain whole number, which is what the task asks to return.
Your turn 4.6. Make a household
The task
Task. Finish make_household(hhid, size): return a Household with the given hhid and size.
| call | returns |
|---|---|
make_household("H00000042", 4) |
Household(hhid="H00000042", size=4) |
If the check is red
Return a Household, not a dictionary or a tuple.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A class like Household is called like a function, with its fields as named values, and gives back a record that has been checked.
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 make_household(hhid, size): return Household(hhid=hhid, size=size)Why each part is there
Household(hhid=hhid, size=size)names each field, so the values cannot land in the wrong place. The names on the left are the class's fields; the ones on the right are the function's inputs.- pydantic converts what it safely can: the check's
make_household('H00000001', '3')gives asizeof the number3, not the text'3'. It refuses what it cannot, such as'three', with aValidationError. - A dictionary such as
{"hhid": hhid, "size": size}holds the same values but checks nothing, so the check turns red: the hint asks for aHousehold.
Your turn 4.7. A number, or nothing
The task
Task. Finish to_number(text): return text as a whole number, or None when it is not one.
| call | returns |
|---|---|
to_number("42") |
42 |
to_number("..") |
None |
If the check is red
Catch only ValueError.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Try the conversion, and if Python says the text is not a whole number, return None instead of stopping.
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 to_number(text): try: return int(text) except ValueError: return NoneWhy each part is there
int(text)does the work and already allows what a whole number may look like: a sign, leading zeros and spaces around it, soint("007")is7andint(" 15 ")is15.- For
"4,2",".."or"-",intraises aValueError.except ValueError: return Nonecatches that one kind of error only, and turns it into the answer the task wants. - Catching every error (
except:orexcept Exception:) would also hide mistakes that are not about the text, such as a misspelt name, and quietly returnNonefor them. That is why the hint says to catch onlyValueError.
Your turn 4.8. Where a round's file is
The task
Task. Finish round_file(round_id): return the path to a round's survey file, which is the file survey.dta in the folder named round_id, inside PATHS.rounds.
| call | returns (as a path inside the course folder) |
|---|---|
round_file("2023Q4") |
rounds/2023Q4/survey.dta |
If the check is red
The result should be a path inside the course folder, ending in survey.dta.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Paths are built from parts with /, starting from the folder the course already knows: PATHS.rounds.
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 round_file(round_id): return PATHS.rounds / round_id / "survey.dta"Why each part is there
PATHS.rounds / round_id / "survey.dta"joins three parts into one path./between paths is not division here; for aPathit means "inside".- Starting from
PATHS.rounds, not from the text"rounds", means the path is right wherever the course folder is and whichever folder the notebook runs from. - Gluing text instead (
"rounds/" + round_id + "/survey.dta") gives a text, not a path: it does not know which folder it is in, and the separator/is not Windows' own.