P1 — Reading Python for ML Labs
About 55 min
This optional guide belongs between Level 0 and L1.1, not inside Level 0. No Python installation is needed. If you get every question below right, you can move to the next lesson. This diagnostic and the exercises do not count toward course progress.
Quick Check
Goal
Read and make small, deliberate edits to the variables, lists, dictionaries, calls, imports, and CSV-reading code in Level 1 Labs. You do not yet need to write complete functions.
Variables and values
An equals sign in Python assigns a value to a name. It is not a mathematical proof of equality.
hours = 2
attendance = 0.70
student = "Mina"
passed = True
print(student, hours, attendance)
For example, if speed = 3 and minutes = 4, the statement distance = speed * minutes multiplies the two numeric values and assigns 12 to distance. The right-hand side is calculated before the assignment.
2 is an integer, 0.70 is a floating-point number, "Mina" is a string, and True is a Boolean. Text needs quotation marks; variable names do not. A comment after # is for the reader and is not executed. Changing hours = 2 to hours = 3 changes the following calculations that read hours; it does not change all the other student records.
print(...) displays what a computation did. When a Lab asks you to compare printed output, read the label as well as the number. An output line saying test ids: [...] is different evidence from one saying accuracy: ....
Lists, dictionaries, and indices
A list holds ordered items between square brackets. Python counts positions from zero.
hours = [2, 5, 4]
print(hours[0]) # 2
print(hours[1]) # 5
hours[1] = 6 # change only the second item
A dictionary connects a key to a value. In L1.2, a dataset can be written as a list of row dictionaries:
rows = [
{"study_hours": 2.0, "attendance": 0.70, "passed": 0},
{"study_hours": 5.0, "attendance": 0.88, "passed": 1},
]
print(rows[0]["attendance"]) # 0.70
Read the expression from left to right: rows[0] gets the first row; ["attendance"] gets that row's named cell. A missing key causes a KeyError; an out-of-range list position causes an IndexError.
Predict
Calls and imports
A function call uses a name and parentheses. For example round(0.756, 2) produces 0.76: the second argument tells round how many decimal places to keep. A named argument writes the setting name explicitly: round(number=0.756, ndigits=2) (both are valid for this built-in).
import csv
from sklearn.model_selection import train_test_split
train_ids, test_ids = train_test_split(
list(range(12)), test_size=0.25, random_state=42
)
print("train/test sizes:", len(train_ids), len(test_ids))
import csv makes that standard-library module available. from ... import train_test_split imports one function from a package. Later, import numpy as np gives NumPy the short name np. list(range(12)) creates twelve integer IDs from 0 through 11; len(...) reports how many items there are. The two names on the left receive the two results returned by train_test_split.
test_size=0.25 holds out approximately one quarter of the examples. random_state=42 fixes a pseudo-random starting state for repeatability; it does not make a split automatically fair or free of leakage. In L1.3, six values are returned when features, targets, and IDs are split together.
Read method calls as operations on an object: model.fit(X_train, y_train) trains it, while model.predict(X_test) asks for predictions. You will learn the model behavior in its own lesson; this guide teaches the call syntax.
Reading comprehensions
You will read short loops in Level 1 before P3 asks you to write them. for means repeating an action for each item; a comprehension builds a new list or dictionary.
rows = [{"hours": 2}, {"hours": 5}]
hours = [row["hours"] for row in rows] # [2, 5]
doubled = {value: value * 2 for value in hours} # {2: 4, 5: 10}
Translate the first line aloud: “For each row in rows, take its hours cell.” For if, for, def, and return, P1 only asks you to recognize the intent. P3 teaches writing them before L2.3.
CSV files and conversion
L1.4 uses a file path rather than hard-coded rows. The following pattern opens a CSV and closes the file safely after the indented block:
import csv
with open("houses.csv", newline="", encoding="utf-8") as handle:
rows = list(csv.DictReader(handle))
price = float(rows[0]["price_thousands"])
with open(...) gives the block a file handle; indentation marks the lines that run while the file is open. csv.DictReader(handle) uses the CSV header as dictionary keys, but all cell values initially arrive as strings. float(...) converts text such as "12.5" to a number. The sample filename illustrates the pattern; it is not a file you need to download for this browser exercise.
Try a TODO in the browser
The browser Lab uses csv.DictReader on an in-memory CSV string, so no local file is required. First run the starter and note that the tests fail. Find the TODO and replace the placeholder result with the value from the first row, converted using float. Run again until all checks pass. Try a different named key to confirm that you are not hard-coding 0.70. The Lab contains three progressive hints and a full checked answer.
Loading lab…
Practice and explain
Take about 10 minutes to predict three edits before running them: change the first attendance value, read "study_hours" instead, and add another CSV row. For each edit, identify whether a value or the number of rows changed. Reset before the next experiment.
Quick Check
Key Takeaways
- Variable names refer to values; strings have quotes, and
printexposes results. - Lists select by zero-based position; dictionaries select by key.
importand calls make library operations available; named arguments supply settings.- Read comprehensions as repeated selections, without writing them from memory yet.
with openmanages a file;csv.DictReaderproduces string-valued row dictionaries.
Continue to P2 — NumPy Arrays and Shapes, or go directly to L1.1 if the skip check was easy.