Ada Kim
+Learning to build for the web
+I like small projects, clear writing and good tea.
+ Say hello +From 64ca1d456d234deaf8fb050a5f31b9dedd29e7b8 Mon Sep 17 00:00:00 2001
From: srivibhavpadakandla
Start at the bottom: KeyError: 'kombucha'. Move up one frame: the crash happened inside price_for, on the line that looks up CATALOGUE[item]. Move up again: price_for was - called from total, which was itself called from line 9, at the - bottom of the file. Reading top to bottom instead tells you the same thing backwards + called from line 9 inside total, which was itself called from line + 12, at the bottom of the file. Reading top to bottom instead tells you the same thing backwards — you would wade through two frames you do not need yet before reaching the one line that actually matters.
diff --git a/src/components/python/FilesAndPathsLesson.tsx b/src/components/python/FilesAndPathsLesson.tsx index 77b95be9..0faff373 100644 --- a/src/components/python/FilesAndPathsLesson.tsx +++ b/src/components/python/FilesAndPathsLesson.tsx @@ -25,7 +25,8 @@ export function FilesAndPathsLesson() { {'open("notes.txt", "w")'} creates the file if it does not exist yet, or empties it if it does — the "w" means write mode.{" "} write() returns the number of characters written, which is easy to - ignore and easy to forget you are ignoring. + ignore and easy to forget you are ignoring. To add to the end of an existing file + instead of wiping it, open it with "a", append mode.+ When a data file lives next to your script, build its path from the script's + own location instead of the folder you happened to run it from.{" "} + __file__ is the path of the current .py file, so{" "} + {'Path(__file__).parent / "notes.txt"'} finds the same file no + matter where the program is started. +
Nothing about this program is specific to counting words — the same shape, a loop filling a dictionary, is the core of a shopping cart total, a vote tally, or a log - file summary. The twenty-four chapters behind this one are not separate tools; they + file summary. The thirty chapters behind this one are not separate tools; they are the vocabulary this one program was written in.
diff --git a/src/components/python/FunctionsLesson.tsx b/src/components/python/FunctionsLesson.tsx index 8691cd42..16f204be 100644 --- a/src/components/python/FunctionsLesson.tsx +++ b/src/components/python/FunctionsLesson.tsx @@ -2,6 +2,7 @@ import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/Le import { Callout } from "@/components/learn/primitives/Callout"; import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; import { FunctionMachine } from "@/components/python/FunctionMachine"; export function FunctionsLesson() { @@ -236,6 +237,30 @@ None`} return. Reaching the end of a function body falls off the end and returns None exactly as if that had been the last line.
+
+ The exact byte counts vary between Python versions, but the gap never closes.
That is not a rounding difference — it is the difference between a container that
already holds a million pointers and an object that holds only the instruction for
how to make the next number, plus a note on where it stopped. The list has to exist
@@ -144,7 +145,8 @@ StopIteration`}
- An open file is an iterator, the same as the list example above — for line
+ An open file is an iterator, like the one iter(numbers) handed back
+ at the start of this chapter — for line
in f: calls next() on it once per line, and each call reads
only as far as the next newline character before handing that one line back.
A package is just a folder of modules, with one marker file,{" "} __init__.py, that tells Python to treat the folder as a single - importable unit rather than an ordinary directory. + importable unit rather than an ordinary directory. The file can be completely + empty; its presence is the signal.
Inside a package, an import can be written two ways. An{" "} absolute import spells out the full path from the top of the @@ -198,7 +206,7 @@ from .shapes import area_of_circle`}
- Most Mac and Linux machines ship with Python already installed. Pick what you are
- sitting at.
+ Most Linux machines ship with Python already installed. On a Mac, the first{" "}
+ python3 may offer to install Apple's command-line developer tools,
+ which include it. Pick what you are sitting at.
+ word[0:2] stops before position 2, so it hands back two + characters, not three. Leave out start and the slice begins at the + front; leave out end and it runs to the finish. Because the end is + excluded, word[:3] + word[3:] always rebuilds the whole string with + nothing doubled and nothing lost. +
+pytest is what turns a scattering of asserts into a suite you run - with one command. It looks for files named test_*.py and functions + with one command (-v asks it to list each test by name). It looks for files named test_*.py and functions inside them named test_*, runs every one it finds, and reports which passed and which raised — no test runner of your own to write.
You pass list, not list() — the type itself, so the dictionary can call it fresh for each new key. Passing list() would - hand over one already-built list, and every key would end up sharing it, which is the - aliasing trap from the previous chapter in one of its least obvious costumes. + hand over one already-built empty list instead of something callable, and{" "} + defaultdict refuses it outright with{" "} + TypeError: first argument must be callable or None.
- One of the four prices was typed as text — {"\"20\""} instead of{" "}
+ One of the two prices was typed as text — {"\"20\""} instead of{" "}
20 — probably because it came from a form field or a spreadsheet
column that nobody checked. Nothing about the program looked wrong until Python
tried to add an int and a string together and had no idea how.
diff --git a/src/components/python/WorkingWithLibrariesLesson.tsx b/src/components/python/WorkingWithLibrariesLesson.tsx
index bd54b99d..e18a5702 100644
--- a/src/components/python/WorkingWithLibrariesLesson.tsx
+++ b/src/components/python/WorkingWithLibrariesLesson.tsx
@@ -53,12 +53,12 @@ Successfully installed requests-2.31.0`}
- python -m venv .venv creates an isolated folder with its own copy of
+ python3 -m venv .venv creates an isolated folder with its own copy of
Python and its own package list.{" "}
source .venv/bin/activate switches the current terminal to use that
copy, so anything installed afterward stays scoped to this one project. The{" "}
diff --git a/src/lib/quizzes/python.ts b/src/lib/quizzes/python.ts
index 87366b93..2fd14ed1 100644
--- a/src/lib/quizzes/python.ts
+++ b/src/lib/quizzes/python.ts
@@ -6,4 +6,1072 @@ import type { AuthoredQuestion } from "@/lib/quizzes/types";
* quiz in src/lib/quiz.ts. Each question tests something the chapter
* actually teaches; `answer` is the zero-based index of the correct option.
*/
-export const QUIZZES: Record
0.5 is the threshold you will see quoted most often, but it is a convention, not a property of geometry. A benchmark can and does choose differently — some standard - evaluations report accuracy at 0.75, a noticeably stricter bar, and some report a whole + evaluations report results at 0.75, a noticeably stricter bar, and some report a whole curve of scores across every threshold from 0.5 to 0.95 rather than commit to one.
diff --git a/src/components/computer-vision/ColourAndChannelsLesson.tsx b/src/components/computer-vision/ColourAndChannelsLesson.tsx index 97300d95..a8b87150 100644 --- a/src/components/computer-vision/ColourAndChannelsLesson.tsx +++ b/src/components/computer-vision/ColourAndChannelsLesson.tsx @@ -2,6 +2,7 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards"; import { InlineCode } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; export function ColourAndChannelsLesson() { return ( @@ -27,7 +28,7 @@ export function ColourAndChannelsLesson() { channel until you ask a specific question about a specific image.
- Green gets nearly five times the weight of blue because human vision is - far more sensitive to green light — your eye has more receptors tuned to that part of - the spectrum than to red or blue. A grayscale conversion that used equal weights would + Green gets about five times the weight of blue because human brightness + perception peaks in the green part of the spectrum: the cones that respond to red and to + green both respond strongly there, while blue-sensitive cones are comparatively few and + contribute little to how bright something looks. A grayscale conversion that used equal + weights would produce a technically valid image that looked wrong to every person who looked at it, because it would not match how brightness actually registers for a human observer.
@@ -71,6 +74,16 @@ export function ColourAndChannelsLesson() { convert to the same grey. The weighting is tuned to human perception, not to the raw light hitting the sensor.- Click through the matrix above and one pair dominates. Cats, dogs and foxes are each - confused with something else once or twice out of fifty — noise, essentially. Wolves and + Click through the matrix above and one pair dominates. Cats, dogs and foxes each lose + only three or four photos out of fifty, scattered one or two at a time across the other + classes — noise, essentially. Wolves and coyotes are a different story: 19 wolves called coyotes, 21 coyotes called wolves, out of 50 of each. That is 40 of the 54 total errors in the entire matrix, from one pair of classes out of five.
That number changes what you would do next. Improving every class’s accuracy by a - point each is 5 points of work for a few points of overall gain. Fixing the wolf/coyote + point each is five separate pieces of work for one point of overall gain. Fixing the wolf/coyote confusion alone — better ear and muzzle features, more training photos of exactly this pair side by side — recovers up to 40 of the 54 errors on its own, which would push - accuracy from 78.4% into the low-to-mid 90s. The matrix tells you where to spend + accuracy from 78.4% to as high as 94.4%. The matrix tells you where to spend the next month, and the single number never could.
diff --git a/src/components/computer-vision/DatasetBiasLesson.tsx b/src/components/computer-vision/DatasetBiasLesson.tsx index 0e7242d9..084fde07 100644 --- a/src/components/computer-vision/DatasetBiasLesson.tsx +++ b/src/components/computer-vision/DatasetBiasLesson.tsx @@ -45,9 +45,9 @@ export function DatasetBiasLesson() {
This is not hypothetical. Joy Buolamwini and Timnit Gebru’s 2018 “Gender - Shades” study tested three commercial facial-analysis systems and found error rates - on darker-skinned women running as high as 34%, against under 1% for lighter-skinned men - on the same systems. The gap was not a mysterious algorithmic quirk — it traced directly + Shades” study tested three commercial systems that classify the gender of a face and + found error rates on darker-skinned women running as high as 34%, against under 1% for + lighter-skinned men on the same systems. The gap was not a mysterious algorithmic quirk — it traced directly back to benchmark and training datasets that were overwhelmingly lighter-skinned and male.
diff --git a/src/components/computer-vision/FaceDetectionAndPrivacyLesson.tsx b/src/components/computer-vision/FaceDetectionAndPrivacyLesson.tsx index c964c4ad..269519c0 100644 --- a/src/components/computer-vision/FaceDetectionAndPrivacyLesson.tsx +++ b/src/components/computer-vision/FaceDetectionAndPrivacyLesson.tsx @@ -55,9 +55,12 @@ export function FaceDetectionAndPrivacyLesson() { title="Error rates that are not even across faces" >- The previous chapter’s Gender Shades findings apply directly here, and soberly: that + The Gender Shades findings from the dataset bias chapter apply here, and soberly: that research measured commercial facial-analysis error rates as high as 34% for darker-skinned - women against under 1% for lighter-skinned men, on systems already deployed commercially. + women against under 1% for lighter-skinned men, on systems already sold commercially. + Gender Shades tested gender classification rather than identity matching, but the U.S. + government’s own testing of face recognition algorithms in 2019 also found error + rates that varied across demographic groups for many of the systems it evaluated. A wrongful match from a recognition system is not an abstract inconvenience — it can mean being stopped, questioned, or investigated for something you did not do.
@@ -71,19 +74,19 @@ export function FaceDetectionAndPrivacyLesson() {- None of this stayed theoretical. Several cities and police departments in the United - States have restricted or banned police use of facial recognition outright, after - documented wrongful arrests traced back to recognition errors. A number of large - companies paused or ended sales of facial recognition to law enforcement following the - same evidence. + None of this stayed theoretical. Several U.S. cities have restricted or banned police + use of facial recognition outright, and documented wrongful arrests traced back to false + matches have since strengthened the case for limits. In 2020, amid public scrutiny that + included independent audits of uneven error rates, a number of large companies paused or + ended sales of facial recognition to police.
+ An edge sits in between. Slide the window across an edge and the view changes sharply; + slide it along the edge and it barely changes at all. That makes an edge locatable in one + direction and ambiguous in the other, which is why detectors prefer corners, where no + direction is ambiguous. +
+ Shift across the edge and the pixels change; shift along it and they do not. You + can pin down one direction, never both. +
+ ), + }, { title: "Corner", tone: "positive", diff --git a/src/components/computer-vision/FromPrototypeToProductionLesson.tsx b/src/components/computer-vision/FromPrototypeToProductionLesson.tsx index 6d281b4e..c287628c 100644 --- a/src/components/computer-vision/FromPrototypeToProductionLesson.tsx +++ b/src/components/computer-vision/FromPrototypeToProductionLesson.tsx @@ -59,7 +59,9 @@ export function FromPrototypeToProductionLesson() { A live video feed at 30 frames per second hands the model a new frame every 33 milliseconds, whether or not it has finished with the last one. A large, highly accurate model that takes 200 milliseconds per frame is not a slower version of a usable system — - it is unusable at that frame rate, full stop, regardless of how it scored offline. + it cannot keep up with that frame rate, regardless of how it scored offline. The only way + to run it is to skip five frames in every six, and whatever happens in those gaps goes + unseen.This is a genuine trade-off against accuracy, not an implementation footnote to solve @@ -108,7 +110,7 @@ export function FromPrototypeToProductionLesson() { items={[ "A benchmark score is a fact about a static test set measured once; it is not a promise about a continuous, real-time production camera feed.", "Deployed cameras drift from what the model trained on through scratched lenses, seasonal white-balance shifts, and newer sensor generations, and the decline is usually gradual, not dramatic.", - "At 30 frames per second a model has roughly 33 milliseconds per frame; a 200-millisecond model is unusable at that rate regardless of its offline accuracy.", + "At 30 frames per second a model has roughly 33 milliseconds per frame; a 200-millisecond model can only keep up by skipping most frames, regardless of its offline accuracy.", "Choosing a smaller, faster, slightly less accurate model to fit the latency budget is a genuine engineering trade-off, not a footnote to accept reluctantly.", "Production traffic has no automatic ground truth, so monitoring means watching proxy signals — confidence-score drift, spikes in low-confidence predictions, user corrections — rather than a clean accuracy number.", ]} diff --git a/src/components/computer-vision/ImageClassificationLesson.tsx b/src/components/computer-vision/ImageClassificationLesson.tsx index 00947b46..5d9d5485 100644 --- a/src/components/computer-vision/ImageClassificationLesson.tsx +++ b/src/components/computer-vision/ImageClassificationLesson.tsx @@ -22,7 +22,7 @@ export function ImageClassificationLesson() {
That narrowness is the whole design, not a limitation someone forgot to - fix. Detection and segmentation, two chapters ahead, exist specifically to + fix. Detection and segmentation, later in this track, exist specifically to answer the questions classification refuses to.
- A well-known example: a model trained to tell huskies from wolves reported 97% - confidence on a photo of a wolf standing in a grassy field — correctly, this time, - identifying it as a wolf, but for the wrong reason entirely. In earlier tests the same - model had called wolves “husky” whenever the photo had snow in the - background, because most of its husky training photos happened to have snow in them - and most of its wolf photos did not. The model had learned to detect snow, not dogs, - and reported startling confidence while doing it. + A well-known demonstration from research on explaining classifiers: a model was + trained to tell huskies from wolves on photos where the wolves were nearly always + pictured against snow. It then labelled a husky standing in snow as a wolf. When the + researchers asked which parts of the image drove the decision, the answer was mostly + the snow, not the animal. The model had learned to detect snow, not wolves, and on + most of its test photos that shortcut happened to give the right answer — which is + exactly why nobody would have noticed from the accuracy alone.
A confidence score describes how sure the model is, not how right it
@@ -100,8 +100,8 @@ export function ImageClassificationLesson() {
tone: "neutral",
children: (
- Right if the true label is anywhere in the model’s five best guesses. Always
- the higher number, and quietly a lower bar.
+ Right if the true label is anywhere in the model’s five best guesses. Never
+ lower than top-1, and quietly a lower bar.
A colour pixel is not one number, it is three — one each for red, green and blue, diff --git a/src/components/computer-vision/MeanAveragePrecisionLesson.tsx b/src/components/computer-vision/MeanAveragePrecisionLesson.tsx index 15b3ad47..049d60da 100644 --- a/src/components/computer-vision/MeanAveragePrecisionLesson.tsx +++ b/src/components/computer-vision/MeanAveragePrecisionLesson.tsx @@ -61,8 +61,11 @@ export function MeanAveragePrecisionLesson() { jagged curve to stand.
- Average precision sidesteps the choice: instead of one threshold, take - the precision value at every point along the sweep and average them. It is a way of + Average precision sidesteps the choice: instead of one threshold, walk + down the sorted list and note the precision each time another real object is caught. + Add those up and divide by the number of real objects in the scene — so an object the + detector never found contributes zero. In the panel above that is (1 + 1 + 1 + 0.8 + + 0.83 + 0.75) / 8 ≈ 0.67. It is a way of scoring the whole trade-off curve with one number instead of committing to a threshold nobody agreed on in advance. Mean average precision then averages that score again, across every object class the detector was tested on — one AP for @@ -82,7 +85,7 @@ export function MeanAveragePrecisionLesson() {
It also treats every miss as equally costly, which is never true in practice. A detector that misses a parked car and one that misses a pedestrian stepping into the road produce - the same one-point deduction to AP, and only one of those two failures matters at + the same deduction from AP, and only one of those two failures matters at highway speed. A single mAP number is a fair summary of overall detection quality and a poor guide to which failures you can actually tolerate.
diff --git a/src/components/computer-vision/NonMaxSuppressionLesson.tsx b/src/components/computer-vision/NonMaxSuppressionLesson.tsx index 8b1e6a2f..f971482f 100644 --- a/src/components/computer-vision/NonMaxSuppressionLesson.tsx +++ b/src/components/computer-vision/NonMaxSuppressionLesson.tsx @@ -48,6 +48,11 @@ export function NonMaxSuppressionLesson() { It is one dog, described twice. Suppressing the extra box loses nothing; keeping it would double-count the same animal in the final result. ++ In practice this runs separately for each class. A box labelled “dog” never + suppresses a box labelled “person”, however much they overlap — someone + holding a puppy is two objects, not one described twice. +
+ Freezing everything is the cautious end of a dial. With a few thousand photos rather + than a few hundred, a common next step is fine-tuning: once the new + head has trained, unfreeze the last few layers of the body as well and keep training + with a small learning rate, so the later, more specific features can adjust to your + images without wiping out what the early layers already know. With very little data, + leave the body frozen; there is not enough to adjust it without overfitting. +
- A car moving at highway speed covers roughly 30 metres every second. Convert that to + A car moving at highway speed — about 110 km/h — covers roughly 30 metres every + second. Convert that to something more concrete: a vision pipeline that takes 200 milliseconds to decide “object ahead, brake” has already let the car travel about 6 metres before the decision even exists, before the brakes have engaged at all. @@ -39,10 +40,10 @@ export function VisionInSelfDrivingCarsLesson() { it is measuring the same thing your eyes measure: visible light bouncing off surfaces.
- That is why no production self-driving system trusts a camera by itself. Radar keeps + That is why most self-driving systems do not trust a camera by itself. Radar keeps working in rain, fog and darkness that would blind a camera, and measures distance and closing speed directly and precisely — but it is weak at telling you what kind of object - it found, a plastic bag and a small dog can look similar to it. Lidar gives precise 3D + it found, and a stationary car and an overhead sign can be hard for it to tell apart. Lidar gives precise 3D distance to every surface it hits regardless of lighting, at real hardware cost, and can struggle with dark or reflective surfaces that absorb or scatter its laser pulses.
@@ -118,8 +119,8 @@ export function VisionInSelfDrivingCarsLesson() {
- Look back at Part 4. Train/test splitting, cross-validation, precision and recall — all
- of it assumed somebody had already written down the right answer for every example, so
+ Look back at Parts 2 and 4. Train/test splitting, cross-validation, precision and
+ recall — all of it assumed somebody had already written down the right answer for every example, so
the model’s answer could be compared against it. That comparison is the entire honesty
toolbox. Take away the right answers and every tool in it stops working, not because
the problem got harder, but because the ingredient they all need is gone.
@@ -172,7 +172,7 @@ export function ClusteringLesson() {
That mess has a number. Gini impurity asks: if you picked a flat from this group at random and guessed its outcome using nothing but the group's own - proportions, how often would you be wrong? An even 50/50 split scores 0.5, the worst - possible. A group where every flat agrees scores 0. + proportions, how often would you be wrong? With two outcomes, an even 50/50 split + scores 0.5, the worst possible. A group where every flat agrees scores 0. The formula + is one minus the sum of each outcome's share squared, so a group that is 80/20 scores + 1 − (0.8² + 0.2²) = 0.32.
To score a candidate split, measure the impurity of both sides, weight each by how many @@ -51,6 +54,16 @@ export function DecisionTreesLesson() { keeps the largest gain. On this data the winner is rent at £697, worth 0.185 — close to the £700 the flats were actually generated around.
++ A worked example makes both concrete. Take an income column whose training values run + from $18,000 to $240,000, with a mean of $60,000 and a standard deviation of $30,000. + An applicant earning $45,000 becomes (45,000 − 18,000) / 222,000 ≈ 0.12 under min-max, + and (45,000 − 60,000) / 30,000 = −0.5 under standardisation: half a standard deviation + below the average earner. +
- SVMs, and anything with a gradient-based penalty on its coefficients — a - column with a huge range needs a huge coefficient to matter, and the penalty - punishes huge coefficients specifically, regardless of whether the size is - doing real work. + SVMs, and any model with a penalty on the size of its coefficients, such as + ridge or lasso — a column with a tiny range needs a huge coefficient to + matter, and the penalty punishes huge coefficients specifically, regardless of + whether the size is doing real work.
PCA — it finds the directions of largest variance, and a column measured in @@ -105,8 +112,8 @@ export function FeatureScalingLesson() { not it carries more signal.
- Neural networks are scale-invariant in principle and slow in practice — - unscaled inputs drag convergence out for far longer than it needs to take. + Neural networks can in principle learn to compensate for any scale, but in + practice unscaled inputs make training slow and unstable.
> ), @@ -124,8 +131,8 @@ export function FeatureScalingLesson() { A split likeTry every value of one number at a resolution of a hundred steps and that is a hundred - tries — an afternoon, and more or less what the last lesson’s bowl already was: a + tries — an afternoon, and more or less what chapter three’s bowl already was: a curve you could have plotted point by point and read the bottom off with your eyes.
@@ -27,7 +28,8 @@ export function GradientDescentLesson() { the tenth power tries. A small neural network has on the order of a million numbers to set, which puts the count at a hundred raised to the millionth power — a figure with no name worth learning, because the point is not the size of the number, it is that grid - search does not slow down as parameters increase. It stops being an option at all. + search does not merely slow down as parameters increase. It stops being an option at + all.
The shape of the search has to change. Instead of trying values, you need a way to be @@ -44,10 +46,10 @@ export function GradientDescentLesson() { are standing, nothing more, and nothing about the rest of the curve required.
- The last lesson’s widget already computed this every time you dragged its slider. - A badge told you which way to nudge the number, and that badge was reading the{" "} + Chapter three’s widget already computed this every time you dragged its slider. + Its “which way is downhill?” panel told you which way to nudge the number, and that panel was reading the{" "} sign of the derivative — positive or negative, downhill left or downhill - right. Gradient descent is that badge with nobody left to read it: the sign alone + right. Gradient descent is that panel with nobody left to read it: the sign alone chooses a direction, and once there is more than one number to move, the same idea applied to all of them at once gets a new name, the gradient.
@@ -63,8 +65,21 @@ export function GradientDescentLesson() { line, once each, every step.
- Set a rate below and press
+ Now set a rate below and press
At 0.03 the same loop reaches 7.761 — within the widget’s own @@ -124,9 +141,9 @@ export function GradientDescentLesson() { card, never handed the wheel.
- You will meet five more words attached to this exact loop before the next chapter is - through. Each one changes a single part of it and none of them replace the update rule - above: + You will meet five more words attached to this exact loop as soon as you read about + training real models. Each one changes a single part of it and none of them replace the + update rule above:
- Every one of those is a variation on the four-word line you already have. The next - lesson stacks that same loop underneath something with vastly more numbers to move — a - neural network — and the loop itself does not change. Only the size of the bowl does. + Every one of those is a variation on the one-line rule you already have. Two chapters + from now, the neural networks lesson stacks that same loop underneath something with + vastly more numbers to move, and the loop itself does not change. Only the size of the + bowl does.
diff --git a/src/components/ml/KNearestNeighboursLesson.tsx b/src/components/ml/KNearestNeighboursLesson.tsx index a14875c2..97cbece1 100644 --- a/src/components/ml/KNearestNeighboursLesson.tsx +++ b/src/components/ml/KNearestNeighboursLesson.tsx @@ -71,8 +71,9 @@ export function KNearestNeighboursLesson() {diff --git a/src/components/ml/NeuralNetworksLesson.tsx b/src/components/ml/NeuralNetworksLesson.tsx index 91a46b1a..4dc73e34 100644 --- a/src/components/ml/NeuralNetworksLesson.tsx +++ b/src/components/ml/NeuralNetworksLesson.tsx @@ -89,8 +89,9 @@ export function NeuralNetworksLesson() { At zero hidden units the widget above is exactly the straight-line model from the first section, and it shows: 62.5% on the points it trained on, 61.7% on the ones it did not — barely past guessing, because half of each ring sits on either side of any line you - could draw. One or two units bend that line slightly and buy almost nothing (69.2%, - then 85.0% training accuracy, with validation trailing well behind at 63.3% and 68.3%). + could draw. One or two units bend that line and help on the training points (69.2%, + then 85.0%), but validation trails well behind at 63.3% and 68.3% — the folds are not + yet in the right places to trace a ring. By three units the fold count catches up with the shape: 99.2% training accuracy, 93.3% held back. Five is where this particular ring stops needing help — 98.3% on data it never trained on, the best any width reaches here. Pushing on to eight buys nothing diff --git a/src/components/ml/PrecisionRecallLesson.tsx b/src/components/ml/PrecisionRecallLesson.tsx index 8aef7fef..4dc8015f 100644 --- a/src/components/ml/PrecisionRecallLesson.tsx +++ b/src/components/ml/PrecisionRecallLesson.tsx @@ -1,4 +1,5 @@ import { Reveal } from "@/components/Reveal"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; import { ThresholdExplorer } from "@/components/ml/ThresholdExplorer"; const SCENARIOS = [ @@ -127,7 +128,7 @@ export function PrecisionRecallLesson() { Arranged in a grid, these four counts are called a{" "} confusion matrix. It is not a thing to memorise — it is just these four numbers in a box. Precision and recall are each - built from three of them. + built from two of them, and they share one: the true positives.
@@ -235,6 +236,17 @@ export function PrecisionRecallLesson() { lopsidedness. Take the extreme case — precision 1.0, recall 0.0. A normal average reports 0.5. F1 reports 0. + +Notice where the gain stops. Between 32 and 120 trees the score moves by half a point. - More trees never makes a forest worse — the average just gets less noisy — but the - returns flatten early. Practitioners pick a few hundred and stop thinking about it, + Past the first handful, more trees do not make a forest worse — the average just gets + less noisy — but the returns flatten early. Practitioners pick a few hundred and stop thinking about it, because the parameter that matters is how the trees are made, not how many.
@@ -135,7 +135,7 @@ export function RandomForestsLesson() { "Feature subsetting limits each split to a random handful of features, which is what stops one strong feature dominating every root.", "Here the forest reached 82.5% against 72.5% for one unrestricted tree and 76.0% for the best pruned one.", "120 trees drew a clean diagonal boundary that no individual member could express.", - "Returns flatten fast — most of the gain arrives by about 30 trees, and more trees never hurt.", + "Returns flatten fast — most of the gain arrives by about 30 trees, and past the first handful more trees do not hurt.", "You lose readability entirely. Feature importances tell you what mattered overall, never why one particular prediction came out as it did.", ]} /> diff --git a/src/components/ml/RegularisationLesson.tsx b/src/components/ml/RegularisationLesson.tsx index a4eb4d5a..226c26d8 100644 --- a/src/components/ml/RegularisationLesson.tsx +++ b/src/components/ml/RegularisationLesson.tsx @@ -166,10 +166,10 @@ export function RegularisationLesson() { />A handful of other files get special treatment on GitHub, all of them optional and all of - them ordinary files in the repository — most can live at the root or in a{" "} - .github/ directory to keep the root tidy. + them ordinary files in the repository. LICENSE belongs at the root; most of the others can + live there or in a .github/ directory to keep the root tidy.
A licence is how you grant the rest. There is no need to write one — pick a standard one, @@ -141,8 +141,8 @@ git switch --detach v1.2.0 # look at the code as it was at that release
A release is a GitHub feature built on top of a tag. It adds release - notes, downloadable binaries, and a pre-release flag. Every release has a tag; most tags are - not releases. + notes, downloadable binaries, and a pre-release flag. Every release has a tag; not every tag is + a release.
- The simplest model that supports review, and by a wide margin the most common on GitHub. One + The simplest model that supports review, and a very common one on GitHub. One permanent branch — main, always deployable — and short-lived branches off it.
Three rules do almost all the work, and the third one surprises everybody. @@ -174,7 +187,7 @@ RESEND_API_KEY=`}
- Check first — you may already have it. macOS ships a Git, and most Linux distributions - install one by default. + Check first — you may already have it. macOS offers to install Apple's Git the first + time you type the command, and many Linux distributions include one.
@@ -111,8 +111,8 @@ git config --global core.editor nano`} Press Esc, then type{" "} :wq and press Enter to save and quit, or :q! to - quit without saving. This is one of the most-searched programming questions of - all time. + quit without saving. Being stuck here is a famously common first experience, so do + not feel bad about it.
- This is the most popular option on GitHub by a wide margin, and the reason is worth stating - plainly: every commit on main builds and passes. Bisect becomes reliable, + Many teams default to this option, and the reason is worth stating plainly: with required + checks, every commit on main builds and passes. Bisect becomes reliable, reverting is one commit with no flags, and the log reads as a list of features rather than a list of afternoons.
@@ -130,7 +130,7 @@ rows and aborted the download. Fixes #482.`}Whether that is good depends on your taste. Some teams want a clean straight line; others - want the record that these three commits were one piece of work reviewed together. Git + want the record that these commits were one piece of work reviewed together. Git lets you insist on the record:
- M is a merge commit, and it is the only kind of commit with two parents. + M is a merge commit, and it is the only kind of commit with more than one + parent. It contains the combined result, it records that these two lines of development joined here, and Git writes its message for you.
@@ -231,7 +232,7 @@ git branch -d fix/login # safe delete: refuses if the work is NOT merged`} "Stand on main and merge the branch to publish work; stand on the branch and merge main to catch up.", "A fast-forward happens when the target has not moved: no commit is created, the label slides.", "--no-ff forces a merge commit anyway; --ff-only refuses to merge unless it can fast-forward.", - "A three-way merge builds a merge commit — the only commit with two parents.", + "A three-way merge builds a merge commit — the only kind of commit with more than one parent.", "The merge base is the most recent shared commit, and it is what lets Git tell an addition from a deletion.", "A line changed on one side is taken silently. A line changed on both sides is a conflict.", "git merge --abort undoes a merge in progress completely.", diff --git a/src/components/github/OpeningAPullRequestLesson.tsx b/src/components/github/OpeningAPullRequestLesson.tsx index c2e7fdcc..ed368066 100644 --- a/src/components/github/OpeningAPullRequestLesson.tsx +++ b/src/components/github/OpeningAPullRequestLesson.tsx @@ -206,7 +206,7 @@ gh pr ready # mark it ready when it is`} }, { label: "The commit tested never existed", - text: "The tested commit is a temporary merge that is not on any branch. This is why a pull request can go red without you pushing anything.", + text: "The tested commit is a temporary merge that is not on any branch. This is why re-running the checks can turn a pull request red without you pushing anything — main moved underneath it.", }, { label: "Required vs optional", @@ -249,7 +249,7 @@ gh pr view --web # open the failing run's logs`} "The description is read by more people than the diff. Say why, and say what you are unsure about.", "A draft pull request cannot be merged and does not request reviewers — good from day one of the work.", "The merge button is gated by required checks, no outstanding changes requested, and enough approvals.", - "Checks run against a temporary merge with the base, not your branch, so a pull request can go red with no push.", + "Checks run against a temporary merge with the base, not your branch, so a re-run can go red with no push from you.", "Small pull requests get reviewed. Large ones get approved.", ]} /> diff --git a/src/components/github/ReadingHistoryLesson.tsx b/src/components/github/ReadingHistoryLesson.tsx index 8038c221..c07536bb 100644 --- a/src/components/github/ReadingHistoryLesson.tsx +++ b/src/components/github/ReadingHistoryLesson.tsx @@ -108,7 +108,7 @@ git log -S "loadUser"`} { label: "git diff", text: "Working tree against the index. What you have changed and NOT staged. Silent if everything is staged." }, { label: "--staged", text: "Index against HEAD. Exactly what your next commit will contain. Read this before every commit." }, { label: "HEAD", text: "Working tree against the last commit. Everything you have done since, staged or not." }, - { label: "a..b", text: "Any two commits, branches, or tags. git diff main..fix/login shows what the branch adds." }, + { label: "a..b", text: "Any two commits, branches, or tags, compared tip to tip. git diff main..fix/login is the same as git diff main fix/login." }, ]} />A rebase takes each of your commits in turn, computes the change it made, and applies that change on top of a different commit. The result is a new commit with the same message, the - same author, the same content — and a different hash, because the parent is different and + same author, the same change — and a different hash, because the parent is different and the hash covers the parent.
- Every commit is now duplicated. If they merge, both copies land and the diff applies twice. + Every commit is now duplicated. If they merge, both copies end up in the history side by + side, and anything they built on the originals is tangled up with your rewritten ones. Untangling this is unpleasant and it is always somebody else's afternoon, not yours.
diff --git a/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx b/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx index 7ec14861..7435d322 100644 --- a/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx +++ b/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx @@ -180,8 +180,8 @@ Untracked files: variant="terminal" code={`# Same information, one line per file, once you know the letters git status --short -# M src/auth/redirect.ts staged modification -# M src/lib/users.ts modified, not staged +# M src/auth/redirect.ts left column: staged +# M src/lib/users.ts right column: modified, not staged # ?? notes.md untracked`} /> @@ -205,12 +205,13 @@ git status --short code={`git add report.md # index now matches disk # ... you keep typing ... git status --short -# M report.md staged: the version from the git add -# M report.md not staged: everything you typed since`} +# MM report.md +# left M: a staged version, from the git add +# right M: newer edits on disk, not staged`} />- The same file appears twice, because there are two different versions of it. The - fix is to git add again before committing. This is not a bug and it is not + The file carries two letters, one per column, because there are two different versions of + it — and in the full git status it is listed under both headings. The fix is to git add again before committing. This is not a bug and it is not a trap — it is exactly the behaviour that makes staging useful — but it is the most common source of "I committed it and the change is not there".
@@ -220,6 +221,25 @@ git status --short every commit catches the half-staged file, the stray debug print, and the accidentally pasted password — in that order of frequency. ++ Try it yourself. Make a throwaway repository and watch one file move + through the three places. The comments are what each command prints. +
+This looks like arbitrary pedantry and it is not. Git itself writes messages in the - imperative when it generates them — "Merge branch feature into main", "Revert - Add the caching layer". Your messages sit in the same list, and matching the mood makes + imperative when it generates them — Merge branch 'feature',{" "} + Revert "Add the caching layer". Your messages sit in the same list, and matching the mood makes the log read as one document rather than a pile of styles.
diff --git a/src/components/github/UndoingThingsLesson.tsx b/src/components/github/UndoingThingsLesson.tsx index c6b8ea03..f64781e0 100644 --- a/src/components/github/UndoingThingsLesson.tsx +++ b/src/components/github/UndoingThingsLesson.tsx @@ -19,9 +19,8 @@ export function UndoingThingsLesson() { title="Name what you regret before picking a command" >
- This chapter exists because the top search result for "git undo" is a Stack - Overflow answer with eleven commands and forty thousand upvotes, and running the wrong one - of them destroys work. + This chapter exists because searching for "git undo" turns up long answers + listing many commands side by side, and running the wrong one of them destroys work.
The reliable method is to stop and say out loud what you want to lose. There are only six
@@ -32,13 +31,13 @@ export function UndoingThingsLesson() {
- git restore overwrites a file in your working tree with the version from
- the last commit. Whatever you had typed is gone — not in the index, not in a commit, not in
+ git restore overwrites a file in your working tree with the version in
+ the index — which is the last commit, unless you had staged a newer version. Whatever you had typed is gone — not in the index, not in a commit, not in
the reflog. Gone.
@@ -191,7 +190,7 @@ git revert HEAD # undo the very last commit, safely`}
One file per branch, each containing one commit hash and a newline. Forty-one bytes. That
diff --git a/src/components/github/WhyVersionControlLesson.tsx b/src/components/github/WhyVersionControlLesson.tsx
index 41989e5e..b0cee3a2 100644
--- a/src/components/github/WhyVersionControlLesson.tsx
+++ b/src/components/github/WhyVersionControlLesson.tsx
@@ -57,8 +57,8 @@ site-final-USE-THIS-ONE (copy)/`}
/>
Git answers all four, and the price is learning a handful of ideas that are
- strange the first time. It is worth it — this is the tool every professional developer on
- earth uses, every day, and it has been the standard for twenty years.
+ strange the first time. It is worth it — this is the tool nearly every software team uses,
+ every day, and it has been around since 2005.
These are the ARIA attributes most likely to appear on a static site:
@@ -172,7 +172,7 @@ export function AccessibilityBasicsLesson() {
@@ -213,7 +213,7 @@ export function AccessibilityBasicsLesson() {
"Read the page with CSS off. That is roughly the screen reader experience",
]}
/>
-
- They all produce the same pixels. The difference is which one you can read and adjust.
+ Hex, rgb, and hsl can describe exactly the same colour; keywords only cover about 140 named
+ ones, so the keyword below is the nearest match rather than the same green. The real
+ difference is which one you can read and adjust.
- A full-width paragraph on a 27-inch monitor is around 200 characters. Which is why an + A full-width paragraph on a large monitor can run past 200 characters a line. Which is why an unstyled page feels hard to read even though nothing is wrong with it.
With an element selected, the Styles panel on the right lists every rule that matched it — - in cascade order, most specific first, with the file and line number each came from. + in cascade order, with the winning rules at the top and the file and line number each came + from.
- Three things in that list explain most of the panel's behaviour. + Four things in that list explain most of the panel's behaviour.
Some text
", label: "p", kind: "element", note: "A sibling of h1. Note it has a child of its own, which is what makes this a tree rather than a list." }, { id: "em", depth: 3, source: " text", label: "em", kind: "element", note: "A child of p, a DESCENDANT of body, and not a child of body. `body > em` matches nothing; `body em` matches this. That distinction is a whole CSS chapter." }, ]; diff --git a/src/components/html-css/ElementsAndTagsLesson.tsx b/src/components/html-css/ElementsAndTagsLesson.tsx index e50cc0b8..0dfe6db4 100644 --- a/src/components/html-css/ElementsAndTagsLesson.tsx +++ b/src/components/html-css/ElementsAndTagsLesson.tsx @@ -91,7 +91,7 @@ export function ElementsAndTagsLesson() { `} />- There are about fourteen in total and those six are all you will use. Note that{" "} + There are thirteen in total and those six are the ones you will use most. Note that{" "} <link> is void — it points at a stylesheet — while{" "} <a>, the one people call a link, wraps content and definitely closes. @@ -121,8 +121,8 @@ export function ElementsAndTagsLesson() { {" "} and{" "} </br>. - There is no content to wrap and nothing to close. Browsers ignore the stray closing - tag, so it looks like it works. + There is no content to wrap and nothing to close. Browsers patch over both — the + stray closing tag is dropped or reinterpreted — so it looks like it works.
), }, diff --git a/src/components/html-css/FlexboxLesson.tsx b/src/components/html-css/FlexboxLesson.tsx index 278c518f..15e466fd 100644 --- a/src/components/html-css/FlexboxLesson.tsx +++ b/src/components/html-css/FlexboxLesson.tsx @@ -2,6 +2,7 @@ import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/Le import { Callout } from "@/components/learn/primitives/Callout"; import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { CompareGrid, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; import { FlexPlayground } from "@/components/html-css/FlexPlayground"; export function FlexboxLesson() { @@ -94,6 +95,15 @@ flex-direction: column-reverse; /* bottom to top */`} main axis is whatever flex-direction says. Toggle direction in the widget above and watch them swap. +Note that the CSS file contains no HTML, no <style> tags, nothing - but rules. Putting a style tag inside a .css file is a common first-day mistake and it - breaks the whole file — everything after it is treated as invalid. + but rules. Putting a style tag inside a .css file is a common first-day mistake: the browser reads + the tag as part of the next selector, decides that rule is invalid, and throws it away — + with no error anywhere.
Those are the image's real pixel dimensions and they are not a display size. The - browser uses the ratio to reserve the right shape, then your CSS scales it. This - is the modern advice and it reverses guidance from about 2015. Older tutorials say the - opposite because browsers used to handle images differently. + browser uses the ratio to reserve the right shape, then your CSS scales it. Some + older tutorials say to leave the dimensions off; that advice dates from before browsers + used them this way, and it no longer applies.
- Without those two lines an 4000-pixel photo blows out your layout on a phone and produces + Without those two lines a 4,000-pixel photo blows out your layout on a phone and produces horizontal scrolling. Three more image rules matter:
- A custom domain costs roughly £10 a year from any registrar and points at your host with + A custom domain is a small yearly fee from any registrar, and it points at your host with one DNS record. Chapter 1 explains why the change takes a while to appear everywhere.
Two bugs account for nearly every "it worked on my laptop" report, and both are @@ -146,7 +146,7 @@ export function PublishingYourSiteLesson() { macOS and Windows treat{" "} Photo.JPG and{" "} photo.jpg as the - same file. Every Linux web server does not. So a mis-cased path works perfectly + same file. Most Linux web servers do not. So a mis-cased path works perfectly locally and 404s the instant you publish.
), @@ -211,7 +211,7 @@ export function PublishingYourSiteLesson() { }, { label: "Run Lighthouse on the live URL", - detail: "The devtools tab audits performance, accessibility, best practices, and SEO in one click. Read the accessibility and SEO sections in particular; they point to specific fixes.", + detail: "The devtools tab audits performance, accessibility, best practices, and SEO in one click. Read the accessibility and SEO sections in particular; they point to specific fixes.", }, ]} /> @@ -232,11 +232,13 @@ export function PublishingYourSiteLesson() { />
@@ -244,10 +245,10 @@ h1 { font-size: clamp(1.75rem, 5vw, 3rem); }
The order of these five passes matters more than any individual rule in them. Each one
settles decisions the next one depends on.
@@ -110,7 +110,7 @@ input, textarea, select, button {
{ label: "Overridable", text: "Redeclare any of these inside a media query or a class and everything using it changes." },
]}
/>
-
+ One token moves in the opposite direction: --accent-ink is the link
+ colour, and a dark green that reads well on a pale page disappears on a dark one, so it
+ flips to a light green. Check every token you use for text, not just the obvious ones.
+
- HTML collapses whitespace on the first page you build:
- any run of spaces, tabs, and newlines becomes a single space.
+ HTML collapses whitespace, and it surprises almost everyone on their first page: any run
+ of spaces, tabs, and newlines becomes a single space.
The escaping-child case is the one that produces a genuine bug report. Anything that
- establishes a new formatting context stops it — padding, a border, or the modern one-liner:
+ separates the two margins stops it — padding or a border on the parent — or the modern
+ one-liner, which gives the parent its own formatting context:
- Step through that and notice how little of it is yours. You write the file in step five.
+ Step through that and notice how little of it is yours. The file the server sends in step five is the one you wrote.
Everything before it is infrastructure you will never touch, and everything after it is the
browser interpreting what you wrote.
+ {starter ? starter.hint : "Edit anything and the preview follows. Share makes a link to exactly this code."}
+
+ {title}
+
+ The preview updates as you type. Press Escape, then Tab, to move focus out of the editor.
+
+ {error ? (
+
+ JavaScript error: {error}
+
+ ) : null}
+ Learning to build for the web I like small projects, clear writing and good tea. Clicked 0 times
At three items this is irrelevant. The trouble is that the code does not change as the
@@ -91,6 +93,7 @@ allowed = {"amara", "ben", "chidi"}
if name in allowed:
...`}
lineTones={{ 6: "ok" }}
+ runnable={false}
/>
The standard library will tell you rather than leave you guessing.
Python passes the object in as self automatically every time you
call a method on it — you never pass it yourself. That is the entire reason every
- method you define takes self as its first parameter.
+ instance method you define takes self as its first parameter.
grace.clubs shows a club she never joined, because{" "}
@@ -201,22 +204,19 @@ True`}
Define __repr__ and that changes: whatever string it returns is
what print, and the console, show instead.
Define it on almost every class you write, not just the ones you plan to print on
diff --git a/src/components/python/ComprehensionsLesson.tsx b/src/components/python/ComprehensionsLesson.tsx
index f98ca715..02a3ea69 100644
--- a/src/components/python/ComprehensionsLesson.tsx
+++ b/src/components/python/ComprehensionsLesson.tsx
@@ -1,8 +1,9 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { Callout } from "@/components/learn/primitives/Callout";
import { LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { ComprehensionSideBySide } from "@/components/python/ComprehensionSideBySide";
+import { TryIt } from "@/components/python/TryIt";
export function ComprehensionsLesson() {
return (
@@ -37,17 +38,15 @@ for n in numbers:
if n % 2 == 0 at the end filters which values make it in, doing the
work of the loop's if check without a separate line.
{"{name: len(name) for name in names}"} builds a dictionary the
same way the loop version would — one key, one value, per iteration. Drop the key
entirely and keep only a value, and a set comprehension collapses duplicates the
- same way set() always does: three names with two distinct lengths
- in unique_lengths produce two entries, not three.
+ same way set() always does: four names with only three distinct
+ lengths produce three entries in unique_lengths, not four.
if tests a condition. If it is true, the indented block underneath
@@ -65,16 +69,21 @@ True`}
only if everything above it was false — and the moment one branch matches, every
branch after it is skipped without being evaluated at all.
A score of 95 matches the first condition and stops there — the{" "}
diff --git a/src/components/python/CopyingAndAliasingLesson.tsx b/src/components/python/CopyingAndAliasingLesson.tsx
index 8df12353..49db2efa 100644
--- a/src/components/python/CopyingAndAliasingLesson.tsx
+++ b/src/components/python/CopyingAndAliasingLesson.tsx
@@ -1,8 +1,9 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { Callout } from "@/components/learn/primitives/Callout";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards";
import { AliasTracer } from "@/components/python/AliasTracer";
+import { TryIt } from "@/components/python/TryIt";
export function CopyingAndAliasingLesson() {
return (
@@ -20,14 +21,14 @@ export function CopyingAndAliasingLesson() {
.copy() when you want a separate list. Here is where that stops
being enough.
b is a separate outer list. It is also holding the exact
@@ -52,6 +53,7 @@ export function CopyingAndAliasingLesson() {
safe = original.copy()
safe = list(original)
safe = original[:]`}
+ runnable={false}
/>
A number cannot be mutated in place, so sharing one is harmless — there is no
@@ -83,8 +85,8 @@ safe = original[:]`}
When you need a copy that shares nothing at all, the standard library has one. It is
not a built-in, and it does not need to be.
deepcopy walks the whole structure and rebuilds every mutable thing
@@ -174,7 +177,10 @@ print(add_badge("cad")) # ['solder', 'cad']`}
if badges is None:
badges = []
badges.append(badge)
- return badges`}
+ return badges
+
+print(add_badge("solder")) # ['solder']
+print(add_badge("cad")) # ['cad']`}
/>
{"@log_calls"} written above{" "}
@@ -148,27 +154,24 @@ calling add
{"@repeat(3)"} to call a function three times, needs one more layer
of nesting than log_calls had.
The first student on each track finds no list, so setdefault puts an
@@ -107,6 +116,7 @@ try:
total += scores["dara"]
except KeyError:
pass`}
+ runnable={false}
/>
The second is the more Pythonic of the two, and not merely by convention. The first
@@ -143,6 +153,7 @@ try:
except KeyError:
total += 0`}
lineTones={{ 3: "err", 4: "err" }}
+ runnable={false}
/>
The second version still crashes if scores turns out to be{" "}
@@ -162,6 +173,7 @@ except KeyError:
code={`minutes = record.get("minutes") # missing key → None, no complaint
average = minutes / chapters # TypeError, forty lines later`}
lineTones={{ 1: "err" }}
+ runnable={false}
/>
The TypeError names the division, which is the one line in the
diff --git a/src/components/python/ErrorsLesson.tsx b/src/components/python/ErrorsLesson.tsx
index 9d3844dd..7b268160 100644
--- a/src/components/python/ErrorsLesson.tsx
+++ b/src/components/python/ErrorsLesson.tsx
@@ -1,9 +1,10 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { Callout } from "@/components/learn/primitives/Callout";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { StepList } from "@/components/learn/primitives/StepList";
import { TakeawayCard } from "@/components/learn/primitives/Cards";
import { ErrorPicker } from "@/components/python/ErrorPicker";
+import { TryIt } from "@/components/python/TryIt";
export function ErrorsLesson() {
return (
@@ -55,7 +56,7 @@ SyntaxError: expected ':'`}
Here is one with more than one frame in it, which is where the bottom-up habit
actually earns its keep.
Inheriting from Exception is enough — pass, with
diff --git a/src/components/python/FilesAndPathsLesson.tsx b/src/components/python/FilesAndPathsLesson.tsx
index 0faff373..ffaa7af7 100644
--- a/src/components/python/FilesAndPathsLesson.tsx
+++ b/src/components/python/FilesAndPathsLesson.tsx
@@ -1,7 +1,8 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { Callout } from "@/components/learn/primitives/Callout";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards";
+import { TryIt } from "@/components/python/TryIt";
export function FilesAndPathsLesson() {
return (
@@ -213,6 +214,17 @@ True`}
{'Path(__file__).parent / "notes.txt"'} finds the same file no
matter where the program is started.
counts.get(word, 0) returns the running total if{" "}
@@ -132,6 +134,7 @@ export function FinalProjectLesson() {
def test_empty_string_returns_empty_dict():
assert word_counts("") == {}`}
+ runnable={false}
/>
@@ -159,7 +162,7 @@ def test_empty_string_returns_empty_dict():
str.strip(string.punctuation) to remove punctuation from the edges
of each word before it becomes a key.
With that change,{" "}
@@ -194,6 +200,14 @@ def word_counts(text):
exactly as the records chapter warned, so pass default=None if
empty input is allowed.
def defines the function once. Every line after it that calls{" "}
@@ -47,6 +49,7 @@ greet("Grace")`}
code={`def greet(name):
"""Print a friendly greeting to the given name."""
print(f"Hello, {name}!")`}
+ runnable={false}
/>
The second call did not start from an empty basket, and nothing about the call site
diff --git a/src/components/python/InheritanceLesson.tsx b/src/components/python/InheritanceLesson.tsx
index 42581758..aeda008f 100644
--- a/src/components/python/InheritanceLesson.tsx
+++ b/src/components/python/InheritanceLesson.tsx
@@ -1,7 +1,8 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards";
import { Callout } from "@/components/learn/primitives/Callout";
+import { TryIt } from "@/components/python/TryIt";
export function InheritanceLesson() {
return (
@@ -82,18 +83,24 @@ True`}
Animal directly, which matters more once a program has several levels of
inheritance.
__init__ is the most common place to reach for super(): a child
@@ -157,21 +164,21 @@ True`}
},
]}
/>
-
Car does not inherit from Engine — it holds one, stored as an
diff --git a/src/components/python/IteratorsAndGeneratorsLesson.tsx b/src/components/python/IteratorsAndGeneratorsLesson.tsx
index 84bf85df..9c08e1f2 100644
--- a/src/components/python/IteratorsAndGeneratorsLesson.tsx
+++ b/src/components/python/IteratorsAndGeneratorsLesson.tsx
@@ -3,6 +3,7 @@ import { Callout } from "@/components/learn/primitives/Callout";
import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards";
import { GeneratorStepper } from "@/components/python/GeneratorStepper";
+import { TryIt } from "@/components/python/TryIt";
export function IteratorsAndGeneratorsLesson() {
return (
@@ -125,6 +126,21 @@ StopIteration`}
the function had never stopped running — the only thing that actually stopped is
your access to the rest of the body, until you ask for more.
This runs in the same, small, constant amount of memory whether{" "}
@@ -212,15 +229,12 @@ StopIteration`}
A generator does not reset once it is exhausted. The second{" "}
diff --git a/src/components/python/JsonAndApisLesson.tsx b/src/components/python/JsonAndApisLesson.tsx
index b99b6c87..3f0d7046 100644
--- a/src/components/python/JsonAndApisLesson.tsx
+++ b/src/components/python/JsonAndApisLesson.tsx
@@ -1,8 +1,9 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { Callout } from "@/components/learn/primitives/Callout";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards";
import { JsonDictToggle } from "@/components/python/JsonDictToggle";
+import { TryIt } from "@/components/python/TryIt";
export function JsonAndApisLesson() {
return (
@@ -54,19 +55,31 @@ export function JsonAndApisLesson() {
comes back through json.loads it is a plain list, not a tuple — the
round trip does not always return the exact type you started with.
json.loads(text) parses a JSON string into an ordinary Python{" "}
@@ -134,6 +147,7 @@ if response.status_code == 200:
data = response.json()
else:
print(f"Request failed: {response.status_code}")`}
+ runnable={false}
/>
Checking response.status_code before touching{" "}
diff --git a/src/components/python/ListMethodsInDepthLesson.tsx b/src/components/python/ListMethodsInDepthLesson.tsx
index 91214c91..7b894c0f 100644
--- a/src/components/python/ListMethodsInDepthLesson.tsx
+++ b/src/components/python/ListMethodsInDepthLesson.tsx
@@ -1,8 +1,9 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { Callout } from "@/components/learn/primitives/Callout";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { CompareGrid, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards";
import { SortKeyPlayground } from "@/components/python/SortKeyPlayground";
+import { TryIt } from "@/components/python/TryIt";
export function ListMethodsInDepthLesson() {
return (
@@ -123,18 +124,16 @@ export function ListMethodsInDepthLesson() {
These two are confused constantly, and the confusion only shows up when what you
are adding happens to be iterable.
One assignment changed three rows, because there are not three rows. There is one
diff --git a/src/components/python/ListsAndTuplesLesson.tsx b/src/components/python/ListsAndTuplesLesson.tsx
index f8c014bf..3d7a4db5 100644
--- a/src/components/python/ListsAndTuplesLesson.tsx
+++ b/src/components/python/ListsAndTuplesLesson.tsx
@@ -1,8 +1,9 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { Callout } from "@/components/learn/primitives/Callout";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { CompareGrid, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards";
import { ListVsTuple } from "@/components/python/ListVsTuple";
+import { TryIt } from "@/components/python/TryIt";
export function ListsAndTuplesLesson() {
return (
@@ -90,16 +91,15 @@ export function ListsAndTuplesLesson() {
the moment you hand a list to a function — the parameter inside the function is
another name on your original list, not a private version of it.
Nothing about add_bonus looks dangerous, and the effect on{" "}
@@ -194,6 +194,19 @@ print(results)
},
]}
/>
+
If the two collections are different lengths, zip() stops as soon
@@ -153,17 +152,15 @@ Alan: 87`}
},
]}
/>
-
Change the list to all-even numbers and the loop finishes without ever hitting{" "}
diff --git a/src/components/python/ModulesAndPackagesLesson.tsx b/src/components/python/ModulesAndPackagesLesson.tsx
index 7fa4fb7c..2c1de731 100644
--- a/src/components/python/ModulesAndPackagesLesson.tsx
+++ b/src/components/python/ModulesAndPackagesLesson.tsx
@@ -1,7 +1,8 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { Callout } from "@/components/learn/primitives/Callout";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards";
+import { TryIt } from "@/components/python/TryIt";
export function ModulesAndPackagesLesson() {
return (
@@ -34,7 +35,7 @@ export function ModulesAndPackagesLesson() {
title: "Package",
tone: "neutral",
children: (
- <>A folder of modules with an __init__.py, importable as one unit.>
+ <>A folder of modules, usually with an __init__.py, importable as one unit.>
),
},
{
@@ -67,12 +68,14 @@ export function ModulesAndPackagesLesson() {
label="shapes.py"
code={`def area_of_circle(radius):
return 3.14159 * radius * radius`}
+ runnable={false}
/>
Nothing about shapes.py changed to make it importable — every{" "}
@@ -118,7 +121,7 @@ print(fetch_forecast("London"))`}
every time — reporting London's forecast into output that has nothing to do
with weather, the moment the import line executes.
__name__ is a variable Python sets automatically in every module.
@@ -147,10 +151,12 @@ if __name__ == "__main__":
- A package is just a folder of modules, with one marker file,{" "}
+ A regular package is a folder of modules with one marker file,{" "}
__init__.py, that tells Python to treat the folder as a single
importable unit rather than an ordinary directory. The file can be completely
- empty; its presence is the signal.
+ empty; its presence is the signal. Python 3 can also import a folder without one,
+ as a namespace package, but that exists for splitting one package
+ across several locations. For your own packages, include the file.
Relative imports save typing inside a large package and keep working if the whole
@@ -215,7 +231,7 @@ from .shapes import area_of_circle`}
Three keys, and the three values are a string, a dictionary, and a list of
@@ -81,6 +86,7 @@ export function NestedStructuresLesson() {
# Amara → solder
# Amara → cad
# Ben → python`}
+ runnable={false}
/>
The outer loop names one member; the inner one names one badge belonging to that
@@ -100,6 +106,7 @@ export function NestedStructuresLesson() {
for badge in member["badges"]
]
# ['solder', 'cad', 'python']`}
+ runnable={false}
/>
@@ -135,13 +142,16 @@ TypeError: string indices must be integers`}
a level that does not exist yet, so building nested data means creating each level
before you fill it.
Both hold three values. Only one of them still makes sense in six months, when{" "}
@@ -52,6 +54,7 @@ student = ("Amara", "python", 18)`}
{"name": "Ben", "track": "ml", "chapters": 6, "minutes": 71},
{"name": "Chidi", "track": "python", "chapters": 24, "minutes": 231},
]`}
+ runnable={false}
/>
This shape is worth recognising on sight, because it is what almost every API hands
@@ -68,15 +71,25 @@ student = ("Amara", "python", 18)`}
matches. Python asks the question of each row instead, and the comprehension you
already know is the whole mechanism.
No index, no counter, and no chance of stopping one row early. What comes back is a
@@ -92,12 +105,22 @@ python_finishers = [
rows are never taken apart, which is why the same one-liner works no matter how many
columns a record has.
Returning a tuple from the key sorts by the first element, then breaks ties with the
@@ -119,6 +142,7 @@ longest = max(students, key=lambda s: s["minutes"])
print(longest["name"])
# Chidi`}
+ runnable={false}
/>
inner() has no local value of its own, so Python
@@ -196,16 +197,15 @@ UnboundLocalError: cannot access local variable 'count'`}
caller has — not a copy of it. What the function does with that reference determines
whether the caller ever notices.
scores inside the function and my_scores outside it
diff --git a/src/components/python/SetsAndTruthinessLesson.tsx b/src/components/python/SetsAndTruthinessLesson.tsx
index 0e96830e..02250758 100644
--- a/src/components/python/SetsAndTruthinessLesson.tsx
+++ b/src/components/python/SetsAndTruthinessLesson.tsx
@@ -1,8 +1,9 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { Callout } from "@/components/learn/primitives/Callout";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { ChecklistCard, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards";
import { TruthinessChecker } from "@/components/python/TruthinessChecker";
+import { TryIt } from "@/components/python/TryIt";
export function SetsAndTruthinessLesson() {
return (
@@ -93,17 +94,17 @@ no votes yet
if votes:. Ask the narrower question instead, and the two cases
separate:
assert condition does nothing at all if{" "}
@@ -92,6 +92,7 @@ test_largest.py::test_empty_list_returns_none PASSED
# Assert
assert result == -5`}
+ runnable={false}
/>
The comments are not required — the value of the shape is that it usually gives each
@@ -159,6 +160,19 @@ test_largest.py::test_empty_list_returns_none PASSED
the inputs a human tester tends to skip, and precisely the ones most likely to break
a real function later.
test_largest says only which function is involved.{" "}
@@ -203,6 +218,7 @@ def sample_scores():
def test_average_of_sample_scores(sample_scores):
assert average(sample_scores) == 88.5`}
+ runnable={false}
/>
sample_scores as a parameter name in{" "}
diff --git a/src/components/python/TheCollectionsModuleLesson.tsx b/src/components/python/TheCollectionsModuleLesson.tsx
index fdca5952..dd8d97ee 100644
--- a/src/components/python/TheCollectionsModuleLesson.tsx
+++ b/src/components/python/TheCollectionsModuleLesson.tsx
@@ -1,8 +1,9 @@
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { Callout } from "@/components/learn/primitives/Callout";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards";
import { CounterBars } from "@/components/python/CounterBars";
+import { TryIt } from "@/components/python/TryIt";
export function TheCollectionsModuleLesson() {
return (
@@ -26,20 +27,24 @@ for colour in colours:
counts[colour] += 1
else:
counts[colour] = 1`}
+ runnable={false}
/>
Six lines that do one thing, and the conditional exists solely because a missing key
raises rather than starting at zero. Counter is a dictionary that
has already decided a missing key means zero.
You pass list, not list() — the type itself, so the
@@ -95,6 +107,7 @@ p = Point(3, 4)
p.x # 3
p[0] # 3 — still an ordinary tuple underneath
x, y = p # still unpacks`}
+ runnable={false}
/>
On a hundred items nobody notices. On a queue of a hundred thousand, processed front
diff --git a/src/components/python/TryIt.tsx b/src/components/python/TryIt.tsx
new file mode 100644
index 00000000..bfd5322f
--- /dev/null
+++ b/src/components/python/TryIt.tsx
@@ -0,0 +1,30 @@
+import { CodeBlock, type CodeLineTone } from "@/components/learn/primitives/CodeBlock";
+import { Tag } from "@/components/learn/primitives/Tag";
+
+interface TryItProps {
+ /** A .py file name, so the block gets a Run button. */
+ label: `${string}.py`;
+ /** A complete program that runs as-is in the browser runner. */
+ code: string;
+ /** One line: what to change before running it again. */
+ prompt: React.ReactNode;
+ lineTones?: Readonly
+
Run this, and predict the output before you check it:
If a variable were a box, a would still read{" "}
diff --git a/src/components/python/WhatIsPythonLesson.tsx b/src/components/python/WhatIsPythonLesson.tsx
index e298ec3c..d83573ff 100644
--- a/src/components/python/WhatIsPythonLesson.tsx
+++ b/src/components/python/WhatIsPythonLesson.tsx
@@ -1,7 +1,8 @@
import { Callout } from "@/components/learn/primitives/Callout";
-import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards";
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
+import { TryIt } from "@/components/python/TryIt";
export function WhatIsPythonLesson() {
return (
@@ -16,7 +17,7 @@ export function WhatIsPythonLesson() {
id="a-language-you-can-read-before-you-can-write-it"
title="A language you can read before you can write it"
>
-
A list of four numbers, a total, an average, and a decision based on it. Nothing in
@@ -118,12 +120,13 @@ ls __pycache__
line actually executes — which might be seconds into a long-running program, or
might be after it has already emailed a customer.
+ The standard library is documented the same way, and it is already installed. The
+ program below uses datetime, which ships with Python.
+
A well-maintained package documents its arguments and return types precisely enough
that you should never need to read its source code to use it correctly — needing to
diff --git a/src/lib/python-lessons.ts b/src/lib/python-lessons.ts
index 6f9ae20d..268b8d65 100644
--- a/src/lib/python-lessons.ts
+++ b/src/lib/python-lessons.ts
@@ -360,7 +360,7 @@ export const PYTHON_CHAPTERS: readonly LearnChapter[] = [
order: 15,
title: "Bundling Data With Behaviour",
description:
- "A dictionary can hold a name and an age, but nothing stops you misspelling the key next time you use it. Define a class once, stamp out three objects from it, and give each its own values without repeating the shape.",
+ "A dictionary can hold a name and a grade, but nothing stops you misspelling the key next time you use it. Define a class once, stamp out three objects from it, and give each its own values without repeating the shape.",
level: "intermediate",
minutes: 11,
prerequisites: ["dictionaries"],
diff --git a/src/lib/quizzes/python.ts b/src/lib/quizzes/python.ts
index 2fd14ed1..b1e5e0c3 100644
--- a/src/lib/quizzes/python.ts
+++ b/src/lib/quizzes/python.ts
@@ -447,7 +447,7 @@ export const QUIZZES: Record
+ Here is IoU as a function, with a 100-by-100 prediction slid further and further right
+ of the true box.
+
+ A 25-pixel slide still scores 0.60, a hit. At 50 pixels it is 0.33, the miss from the
+ exercise above. Change the threshold to 0.75 and the 25-pixel box becomes a miss
+ without moving.
+
+ A two-pixel image, a sky and a leaf, pulled apart into channels, turned grey, and then
+ read in the wrong channel order.
+
+ The weighted grey for the sky is 188, as in the exercise above. Reversed, the sky
+ becomes 235, 206, 135, a pale orange, while the leaf barely changes, because its red
+ and blue were close to begin with.
+
+ Try it on real images: a deliberately weak digit classifier, then the off-diagonal
+ cells sorted by count.
+
+ Overall it scores 84.4%. The biggest single error is 21 eights called ones, then 16
+ threes called nines. Change the 60 training images to 300 and see which confusions
+ survive.
+
+ Here is the whole operation written by hand, run on a 5-by-5 patch of 10s with one
+ bright 100 in the middle.
+
+ Blur writes 20 everywhere, because every 3-by-3 window here contains the bright pixel.
+ Sharpen writes 460 in the centre and −80 beside it. Only the 8-bit copy clips those to
+ 255 and 0. Swap in your own kernel and run it again.
+
+ You can check the 2n + 1 rule by following a single pixel through a stack of 3-by-3
+ layers.
+
+ Each layer adds two pixels: 3, 5, 7, 9, then 11 after five layers.
+
Depth is not free. More layers means more parameters to learn, more
computation for every photo you show it, and a model that needs far more labelled
diff --git a/src/components/computer-vision/DatasetBiasLesson.tsx b/src/components/computer-vision/DatasetBiasLesson.tsx
index 084fde07..60c302cc 100644
--- a/src/components/computer-vision/DatasetBiasLesson.tsx
+++ b/src/components/computer-vision/DatasetBiasLesson.tsx
@@ -1,5 +1,6 @@
import { Callout } from "@/components/learn/primitives/Callout";
import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards";
+import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
export function DatasetBiasLesson() {
@@ -86,6 +87,29 @@ export function DatasetBiasLesson() {
blended average. It is unglamorous and it is the only method that reliably surfaces a
gap an overall score is mathematically built to hide.
+ A generated test set where one group makes up about 4% of the photos and the model is
+ much worse on it. One overall number, then the same results grouped.
+
+ Overall accuracy is 96.4%. Grouped, it is 97.1% for the well-represented photos and
+ 79.1% for the rest.
+
+ Here it is on a tiny wall with a darker doorway, plus a little sensor noise. Each
+ pixel is compared with its right neighbour and the one below.
+
+ Inside the wall and the doorway the slope stays under 20; along the door frame it
+ jumps past 75. A threshold of 40 keeps just the frame. Drop it to 5 and the noise
+ starts drawing lines of its own.
+
+ Here is that test as arithmetic, on a bright square. The score adds up how brightness
+ changes across and down a small window, and is only large when it changes in both
+ directions at once.
+
+ The flat patch scores 0, the edge scores below 0, and the corner scores 1.74. This is
+ the idea behind the Harris corner detector.
+
A live video feed at 30 frames per second hands the model a new frame every 33
- milliseconds, whether or not it has finished with the last one. A large, highly accurate
- model that takes 200 milliseconds per frame is not a slower version of a usable system —
- it cannot keep up with that frame rate, regardless of how it scored offline. The only way
- to run it is to skip five frames in every six, and whatever happens in those gaps goes
- unseen.
+ milliseconds, whether or not it has finished with the last one. Take a large, highly
+ accurate model that needs 200 milliseconds per frame, running on a single worker. That
+ worker cannot keep up with the frame rate, regardless of how the model scored offline:
+ it has to skip five frames in every six, and whatever happens in those gaps goes unseen.
+
+ Two numbers are tangled together here. Throughput is how many frames
+ per second the system can get through; latency is how long any one
+ frame waits for its answer. Running six or seven copies of the model side by side, each
+ taking every sixth or seventh frame, can bring throughput back up to 30 frames per
+ second, at the cost of that much more hardware. It does nothing for latency. Every
+ answer still arrives at least 200 milliseconds after its frame, which for a robot arm
+ or a car can already be too late.
+
+ A three-second simulation of a 30 fps feed and a 200 ms model, with one worker and
+ then seven.
+
+ One worker processes 15 of the 90 frames. Seven process all 90. Either way, every
+ answer arrives 200 ms after its frame.
This is a genuine trade-off against accuracy, not an implementation footnote to solve
- later. A smaller, faster, slightly less accurate model that keeps up with 33 milliseconds
- per frame is often the only real option; a bigger model that cannot keep up does not get
- partial credit for its offline score.
+ later. A smaller, faster, slightly less accurate model that fits inside 33 milliseconds
+ per frame on the hardware you actually have is often the only real option; a bigger model
+ that cannot keep up does not get partial credit for its offline score.
+ Four photos, six classes, and a model’s probabilities for each. Rank the guesses
+ and score them both ways.
+
+ Only the first photo’s best guess is right, so top-1 accuracy is 25%. Every
+ correct answer is somewhere in the top three, so top-3 accuracy is 100%. Same model,
+ same probabilities.
+
+ Both halves of that in one run. Normalising uses numbers from the training photos only,
+ and then a 6 from the test set is rotated by 180 degrees.
+
+ The model reads the 6 correctly, and calls the rotated one a 9. If that rotation were
+ used as augmentation, the training set would be full of 9s labelled 6.
+
+ A small semantic mask with two round dogs. First, how much of a box around one of them
+ is not dog; then, counting the dogs by finding connected blobs.
+
+ 32 of the 81 pixels in the box are background. The blob count finds two dogs, but only
+ while they do not touch. Move them together and the same mask reports one.
+
+ Build a small face from nothing but numbers, then halve its resolution by averaging
+ each 2-by-2 block into one pixel.
+
+ 144 numbers become 36, and the eyes and mouth smear into two greys. Change the 200 or
+ the 30 and rerun to see that the picture is nothing but those values.
+
+ The panel’s ten detections, walked down by hand.
+
+ It prints the same 0.67. Flip one of the last two detections to True and see how much
+ a single late hit is worth.
+
+ The six boxes from the interactive, run through the algorithm at three thresholds. All
+ of them are labelled dog, so every box is compared with every kept box.
+
+ At 0.5 it keeps a and f, one box per dog. At 0.1 the second dog’s box f is
+ swallowed by a, and at 0.9 all six survive.
+
+ The same failure shows up on real handwriting. This model gives every pixel of an
+ 8-by-8 digit its own weight, then is tested on digits nudged one or two pixels to the
+ right.
+
+ It reads 95% of the digits as drawn, 40% after a one-pixel shift, and 9% after two.
+ Nothing about the digits changed except where they sit.
+
A convolution kernel, from the earlier chapter on filters, fixes exactly this failure.
Instead of one independent weight per pixel position, a kernel is a small set of
diff --git a/src/components/computer-vision/WhatIsComputerVisionLesson.tsx b/src/components/computer-vision/WhatIsComputerVisionLesson.tsx
index 710e1f09..166a17ad 100644
--- a/src/components/computer-vision/WhatIsComputerVisionLesson.tsx
+++ b/src/components/computer-vision/WhatIsComputerVisionLesson.tsx
@@ -1,5 +1,6 @@
import { Callout } from "@/components/learn/primitives/Callout";
import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards";
+import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { StepList } from "@/components/learn/primitives/StepList";
@@ -33,6 +34,30 @@ export function WhatIsComputerVisionLesson() {
what that object is called — has to be built back up from those numbers by something
else. That something else is the entire subject of this track.
+ You can look at that wall of numbers yourself. scikit-learn ships with a set of small
+ handwritten digits; here is the first one.
+
+ The array is the image. The picture underneath is drawn from those same 64 numbers,
+ and nothing in them says “zero”.
+
+ The same idea in a few lines, on freshly generated data. Normal is described by the
+ ordinary rows only, and nothing here ever trains on a fraud.
+
+ At a cut-off of 2.0 it catches 7 of the 9 frauds with 57 false alarms. At 3.0 the
+ false alarms fall to 5 and only 3 frauds are caught.
+
Notice that no setting is correct. The precision-recall lesson made
the same point about a threshold on a classifier's confidence, and it applies here
diff --git a/src/components/ml/BaselinesLesson.tsx b/src/components/ml/BaselinesLesson.tsx
index 99ee8756..41b637e6 100644
--- a/src/components/ml/BaselinesLesson.tsx
+++ b/src/components/ml/BaselinesLesson.tsx
@@ -1,5 +1,6 @@
import { Callout } from "@/components/learn/primitives/Callout";
import { ChecklistCard, TakeawayCard } from "@/components/learn/primitives/Cards";
+import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { BaselineBoard } from "@/components/ml/BaselineBoard";
@@ -90,6 +91,44 @@ export function BaselinesLesson() {
Written in a slide with no baseline beside it, that reads as a working model. It is a
working model that is worse than one line of code, and only the baseline says so.
+
+ The same race on fresh data: one column that matters, five that do not, and two of
+ scikit-learn’s ready-made dummy models as the floor.
+
+ The majority rule scores 54.7% and guessing at the right rate 48.7%. The stump gets
+ 89.3%. The neighbour vote (88.0%) and the depth-6 tree (87.3%) come close but do not
+ beat it.
+
+ Here is the same comparison on a fresh set of generated transactions, about one in
+ fifty fraudulent.
+
+ Flagging nothing scores 98.1% accuracy. The plain model at 0.5 catches 5% of frauds;
+ class weighting catches 80% by flagging 707 transactions. Lowering the plain
+ model’s cut-off to 0.02, with no retraining, lands next to it: 77% recall, 6%
+ precision, 684 flagged.
+
+ Try it with your own numbers. One regression model predicts delivery minutes; then the
+ very same predictions are rounded into 2, 5 and 20 equal-width buckets and scored as
+ categories.
+
+ The average miss is 4.7 minutes, and accuracy falls from 88% to 60% to 19% as the
+ buckets narrow. The predictions never changed. Only the question did.
+
+ Run k-means for k = 1 to 8 on 300 generated points that really do come from three
+ groups.
+
+ Inertia drops from 8,029 to 1,477 to 760, and after that each extra centre buys only
+ around a hundred: 648, 554, 467. The elbow is at 3. Change{" "}
+
There is a second assumption buried in the method itself, and it is easy to miss
because nothing in the algorithm checks it. Distance to a single centre is only a
diff --git a/src/components/ml/CrossValidationLesson.tsx b/src/components/ml/CrossValidationLesson.tsx
index b08a6a2d..6f3656e0 100644
--- a/src/components/ml/CrossValidationLesson.tsx
+++ b/src/components/ml/CrossValidationLesson.tsx
@@ -1,5 +1,6 @@
import { Callout } from "@/components/learn/primitives/Callout";
import { TakeawayCard } from "@/components/learn/primitives/Cards";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { FoldRotator } from "@/components/ml/FoldRotator";
@@ -63,6 +64,31 @@ export function CrossValidationLesson() {
model scoring 4.31 give or take 0.1 and a model scoring 4.31 give or take 2.2 are not
the same result, and only one of them is worth defending.
+ Here are five folds on a small dataset bundled with scikit-learn: 178 wines, 13
+ chemical measurements each, and three grape varieties to tell apart.
+
+ The folds score between 0.83 and 0.97, averaging 0.93. Set{" "}
+
The bottom panel makes the payoff concrete. Repeat the whole experiment forty times with
forty different shuffles. Report from a single 20% holdout and you land somewhere across
diff --git a/src/components/ml/DataLeakageLesson.tsx b/src/components/ml/DataLeakageLesson.tsx
index 28a7828f..d57f8d81 100644
--- a/src/components/ml/DataLeakageLesson.tsx
+++ b/src/components/ml/DataLeakageLesson.tsx
@@ -1,5 +1,5 @@
import { Callout } from "@/components/learn/primitives/Callout";
-import { InlineCode } from "@/components/learn/primitives/CodeBlock";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { ChecklistCard, TakeawayCard } from "@/components/learn/primitives/Cards";
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { LeakInspector } from "@/components/ml/LeakInspector";
@@ -119,6 +119,40 @@ export function DataLeakageLesson() {
their scaler while their table has three rows per customer is worrying about the wrong
end.
+ Not every whole-dataset step is that harmless. Choosing columns is the one that bites.
+ Below are 5,000 columns of pure noise and labels decided by a coin flip, so there is
+ nothing to learn and the honest score is about 50%.
+
+ Pick the twenty best-looking columns using every row and the cross-validated score
+ comes out at 85%. Do the picking inside each fold, on training rows only, and it drops
+ to 48%. The leaky version did not find a pattern: it chose the columns that happened
+ to match the test rows’ coin flips.
+
+ The same pattern on generated data with 15% of the labels flipped at random. Each line
+ grows a tree to a different maximum depth.
+
+ Training accuracy climbs all the way to 100%. Held-back accuracy peaks at 85% at
+ depths 2 and 3, then slides to 78% once the tree has grown 63 leaves to fit the
+ flipped labels.
+
+ Here is that curve, as numbers, for a real 64-column dataset: scikit-learn’s
+ 8-by-8 images of handwritten digits, one column per pixel.
+
+ Two components keep 29% of the variance, ten keep 74%, and twenty keep 89%. Thirty
+ components, under half the columns, keep 96%. Where you stop depends on what you need
+ the result for.
+
+ A curved but order-preserving transform, such as taking the log of income,
+ is slightly different. Each split still separates the same training rows,
+ but the cut-off can land at a different point in the gap between two training
+ values, so a new applicant who falls inside that gap can switch sides.
+ Check both halves of that on generated loan data. The same k-NN and the same tree are
+ trained twice, once in raw units and once standardised.
+
+ k-NN goes from 61.7% in raw units to 90.8% once standardised. The tree scores 93.3%
+ both times: stretching and shifting a column only moves its cut-offs.
+
+ The same experiment in code. Each column gets the single best cut a one-question
+ decision tree can find, and then so does an invented column that mixes the two.
+
+ Minutes alone gets about 91%, oven temperature alone about 59%, and the invented
+ feature 97%. One honest caveat: this data was generated from that exact mix, so here
+ the invented feature wins by construction. With real loaves you would not know the
+ recipe, and finding a good mix is the work.
+
+ Checking an input needs nothing but the inputs. This uses a different drift score from
+ the panel above, the Kolmogorov–Smirnov statistic, which measures how far apart two
+ distributions are.
+
+ The two ordinary months score 0.05 and 0.06. The month after the price rise scores
+ 0.44 and gets flagged. A check like this only catches input drift: if the inputs stay
+ the same and the right answers change, it sees nothing.
+
And you keep the baseline from chapter fourteen running, permanently, in parallel. It
cost half an hour to build and nothing to keep running. When labels do eventually land,
diff --git a/src/components/ml/GradientDescentLesson.tsx b/src/components/ml/GradientDescentLesson.tsx
index ecf27b38..5d843b40 100644
--- a/src/components/ml/GradientDescentLesson.tsx
+++ b/src/components/ml/GradientDescentLesson.tsx
@@ -107,6 +107,37 @@ export function GradientDescentLesson() {
climbing. At 1.02 one step is enough — the parameter jumps from 0.5 to
119.64 and the error goes from 426.72 to 100,058.73 before a second step is ever taken.
+ Here is the loop with two numbers instead of one: a slope and a starting height,
+ fitted to fifty generated points whose true values are 3 and 1.
+
+ At 0.1 it reaches a slope of 3.065 and a start of 1.010 within twenty steps. Try 0.01
+ and after forty steps it is still crawling. Try 0.8 and every step overshoots further
+ than the last until the numbers run away.
+
+ You can do the whole search in a few lines. Score a handful of settings, then try
+ every setting from 4 to 11 in steps of 0.01 and keep whichever leaves the least total
+ squared error.
+
+ The errors fall and then rise again — the bowl, as numbers — and the lowest lands at
+ 7.40 L/100km. The trips were generated at 7.5, so even the best setting is not the
+ true one: the noise in thirty-six trips pulls it slightly off.
+
Real models have millions of numbers instead of one, and the bowl becomes a landscape
in millions of dimensions that nobody can picture. But the move is identical, and you
diff --git a/src/components/ml/KNearestNeighboursLesson.tsx b/src/components/ml/KNearestNeighboursLesson.tsx
index 97cbece1..ec6e15fb 100644
--- a/src/components/ml/KNearestNeighboursLesson.tsx
+++ b/src/components/ml/KNearestNeighboursLesson.tsx
@@ -1,5 +1,6 @@
import { Callout } from "@/components/learn/primitives/Callout";
import { TakeawayCard } from "@/components/learn/primitives/Cards";
+import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { NeighbourVote } from "@/components/ml/NeighbourVote";
@@ -86,9 +87,10 @@ export function KNearestNeighboursLesson() {
“Nearest” means nearest by some measurement, and the obvious measurement is
straight-line distance. Revision hours run from 0 to 12. Previous scores run from 20 to
100. A gap of ten points on the previous exam and a gap of ten hours of revision count
- the same in that sum — and since the score axis is nearly seven times wider, a typical
- gap along it is nearly seven times bigger, and it dominates the distance. The model is not weighing your features. Your
- units are.
+ the same in that sum. In this class, two students typically sit about 19 points apart
+ on previous score but under 4 hours apart on revision, so the score gap is about five
+ times bigger, and it dominates the distance. The model is not weighing your features.
+ Your units are.
Select Coasting on a good record: two hours of revision, a previous
@@ -111,6 +113,39 @@ export function KNearestNeighboursLesson() {
underperforms — and because the code still runs and still reports a number, nothing
announces the mistake.
+ Run the same comparison on a fresh class of 120 generated students: once in raw units,
+ once with both features squashed onto 0 to 1.
+
+ At k = 1 and 3 the two are close. From k = 7 the raw version falls apart, to 67%, then
+ 58% and 56%, because a bigger vote reaches further and in raw units further means
+ along the score axis. The scaled version holds at 92% to 94%.
+
One caution that will matter later: work out the scaling from the training data alone.
If you compute the minimum and maximum across the whole dataset before splitting, the
diff --git a/src/components/ml/NeuralNetworksLesson.tsx b/src/components/ml/NeuralNetworksLesson.tsx
index 4dc73e34..42cf4b94 100644
--- a/src/components/ml/NeuralNetworksLesson.tsx
+++ b/src/components/ml/NeuralNetworksLesson.tsx
@@ -99,6 +99,35 @@ export function NeuralNetworksLesson() {
at five. The extra capacity is not fitting the ring any better. It is chasing individual
training points that happened to land where they did.
+ The same two rings, generated fresh, with scikit-learn’s small neural network
+ and one hidden layer of ReLU units.
+
+ A straight line scores 42%, no better than guessing, and so does one hidden unit. Two
+ units reach 64%, three reach 99%, and eight score 96% on the held-back points: more
+ width did not help here.
+
That is width — more units in the same layer, each one a fresh fold
available at once. Depth is the other axis: more layers, stacked, so a
diff --git a/src/components/ml/OverfittingLesson.tsx b/src/components/ml/OverfittingLesson.tsx
index 51653f97..33331f59 100644
--- a/src/components/ml/OverfittingLesson.tsx
+++ b/src/components/ml/OverfittingLesson.tsx
@@ -1,5 +1,6 @@
import { Callout } from "@/components/learn/primitives/Callout";
import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards";
+import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { DegreeDial } from "@/components/ml/DegreeDial";
@@ -77,6 +78,38 @@ export function OverfittingLesson() {
the fitted curve sits close to it. At twelve it is chasing individual dots and has
wandered off the truth entirely, in places predicting scores that could not exist.
+ Here is the slider as a loop: fifteen students to fit, two hundred new ones to test
+ on, and polynomial curves with more and more bends.
+
+ Training error falls at every step, from 195 down to 3.7. Test error bottoms out at
+ degree 2, which is the shape the data was generated from, and by degree 12 it has
+ exploded past 22,000. Same students, same code; only the number of bends changed.
+
+ Now with a thousand made-up transactions and a model’s confidence score for
+ each. Choose a threshold, count the four boxes, and build precision, recall and F1
+ from them by hand.
+
+ At 0.5 it finds 87 of the 102 frauds (recall 0.85) while 142 legitimate transactions
+ get flagged too (precision 0.38). Set the threshold to 0.3 and recall reaches 0.99
+ as precision drops to 0.15; at 0.7 precision rises to 0.89 and recall falls to 0.48.
+
- Notice where the gain stops. Between 32 and 120 trees the score moves by half a point.
- Past the first handful, more trees do not make a forest worse — the average just gets
- less noisy — but the returns flatten early. Practitioners pick a few hundred and stop thinking about it,
- because the parameter that matters is how the trees are made, not how many.
+ Notice where the gain stops. Between 32 and 120 trees the score only wobbles within a
+ point: 82% at 32, 81% at 50, back to 82.5% at 120. Adding trees does not make a forest
+ systematically worse. The vote just gets less noisy, and on a test set this small a
+ single flat or two changing sides moves the score up or down a little. But the returns
+ flatten early. Practitioners pick a few hundred and stop thinking about it, because the
+ parameter that matters is how the trees are made, not how many.
+
+ Try it on a different dataset. One unrestricted tree first, then forests of increasing
+ size.
+
+ The single tree scores 72.8%. A forest of one tree does worse, 60.6%, because that
+ lone tree was trained on a bootstrap sample with a limited choice of features at each
+ split. By 25 trees the forest reaches 80.6%, and after that the score only wobbles:
+ 80.0% at 100 and 79.4% at 200.
+ Fit both penalties to forty rows and eight columns, where only the first three columns
+ carry any real signal.
+
+ Ridge shrinks every coefficient and sets none of them to exactly zero; the one that
+ prints as
There is a compromise between the two — elastic net, which penalises
with a blend of both sums at once — for when you want some sparsity without betting
diff --git a/src/components/ml/TrainTestSplitLesson.tsx b/src/components/ml/TrainTestSplitLesson.tsx
index 683e4945..2831586e 100644
--- a/src/components/ml/TrainTestSplitLesson.tsx
+++ b/src/components/ml/TrainTestSplitLesson.tsx
@@ -1,5 +1,6 @@
import { Callout } from "@/components/learn/primitives/Callout";
import { TakeawayCard } from "@/components/learn/primitives/Cards";
+import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock";
import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection";
import { SplitLottery } from "@/components/ml/SplitLottery";
@@ -80,6 +81,40 @@ export function TrainTestSplitLesson() {
and it is the model flattering itself. Never quote a training score as though it were
a measure of how good your model is.
+ Both effects show up on a real dataset that ships with scikit-learn: 569 breast
+ tumours, each described by 30 measurements. An unrestricted decision tree is graded on
+ what it studied, then on the drawer, and then the drawer is redrawn ten times.
+
+ The tree scores 100% on its own training rows and 88% on the drawer. With a 5% drawer
+ the ten scores run from 79% to 100%; change
+ Here is the voting rule from the top of the page again, except this time nobody writes
+ it. The model gets ten example people, their ages, and whether each one could vote,
+ and has to find the rule itself.
+
+ It prints {eyebrow} {lead} {lead} {step.body}
- Listed in no particular order. CodeWithPurpose isn’t affiliated with any of these companies.
- {item.why} {step.body} {group.blurb} {tool.description}
+ Listed in no particular order. CodeWithPurpose isn’t affiliated with any of these companies.
+ {rule.body}
- Our free Vibe Coding course walks you through building real projects with AI, one step at a
- time. Questions along the way? Ask the community.
+ {/* Next steps */}
+
+ Our free Vibe Coding course walks you through building real projects with AI, one step at a time.
+ Or try some code right now in the playground.
+ Questions along the way?{" "}
+
+ Ask in our Discord
+ (opens in a new tab)
+
+ 2. Fill in the blanks 3. Copy your prompt
+ Paste it into any AI chat. What you type here stays on this page.
+
+
{hasProgress ? "Saved on this device" : "Free, interactive, and saved as you go"}
Entering course Entering course {active.title}
- Chapters unlock in order. Pass the quick check on{" "}
- {prev.title}, and this one opens
- up.
+ Finish the quick check at the end of{" "}
+ {prev.title}, and this chapter
+ opens up.
or pressing Enter.",
"strong is importance, em is stress emphasis; b and i are conventional appearance with no added meaning.",
- "blockquote, code, time, abbr and cite all say something a span would not.",
+ "blockquote, q, code, time, abbr and s all say something a span would not.",
"Write < > & as entities. With utf-8 everything else can be typed directly.",
"Comments are ignored by the browser and fully visible in view source.",
]}
diff --git a/src/components/html-css/TheBoxModelLesson.tsx b/src/components/html-css/TheBoxModelLesson.tsx
index c157e24c..21286c71 100644
--- a/src/components/html-css/TheBoxModelLesson.tsx
+++ b/src/components/html-css/TheBoxModelLesson.tsx
@@ -2,13 +2,14 @@ import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/Le
import { Callout } from "@/components/learn/primitives/Callout";
import { CodeBlock } from "@/components/learn/primitives/CodeBlock";
import { CompareGrid, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards";
+import { RevealCard } from "@/components/learn/primitives/RevealCard";
import { BoxModelExplorer } from "@/components/html-css/BoxModelExplorer";
export function TheBoxModelLesson() {
return (
for a line of text only because they wanted it smaller. What is wrong with that?",
+ options: [
+ "Size is a CSS question; the tag should say what the content is",
+ "An h3 cannot be used unless there is an h4 straight after it",
+ "Browsers refuse to render an h3 that is not inside a section",
+ "Nothing; picking tags by how they look is the intended approach",
+ ],
+ answer: 0,
+ },
+ {
+ q: "Which of these features genuinely needs JavaScript?",
+ options: [
+ "Search results that update live as you type",
+ "A link that takes you to another page",
+ "A form that submits to the server",
+ "Headings shown in decreasing sizes",
+ ],
+ answer: 0,
+ },
+ {
+ q: "A well-built page loads with its stylesheet missing. What should the visitor see?",
+ options: [
+ "Plain but readable content: black text, blue links, sized headings",
+ "A blank white page until the stylesheet finally arrives",
+ "An error message saying the page could not be displayed",
+ "The raw HTML source with all of the tags visible as text",
+ ],
+ answer: 0,
+ },
+ {
+ q: "Why are script tags conventionally placed at the end of the body, or given the defer attribute?",
+ options: [
+ "A script in the middle stops HTML parsing until it downloads and runs",
+ "Scripts placed in the head are ignored by every modern browser",
+ "The DOM cannot be built at all until every script has finished",
+ "CSS rules are not applied to elements that come after a script",
+ ],
+ answer: 0,
+ },
+ ],
+ "your-first-page": [
+ {
+ q: "You save index.html in Notepad on Windows, but double-clicking it opens it as plain text. What is the most likely cause?",
+ options: [
+ "It was saved as index.html.txt, hidden because extensions are off",
+ "The file is missing a `,
+ ].filter(Boolean);
+ try {
+ await navigator.clipboard.writeText(parts.join("\n\n"));
+ setCopied(true);
+ window.clearTimeout(copiedTimer.current);
+ copiedTimer.current = window.setTimeout(() => setCopied(false), 1600);
+ } catch {
+ // Clipboard access can be refused; the code is still selectable.
+ }
+ };
+
+ return (
+
Ada Kim
+ Plants I grow
+
+
`,
+ css: `body {
+ font-family: system-ui, sans-serif;
+ margin: 0;
+ padding: 20px;
+ background: #fcf4e8;
+ color: #15120c;
+}
+
+h1 {
+ font-size: 1.5rem;
+ margin-top: 0;
+}
+
+.grid {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: 12px;
+}
+
+.grid li {
+ padding: 28px 16px;
+ border-radius: 14px;
+ background: #dbefdb;
+ text-align: center;
+ font-weight: 600;
+ color: #1e3c2c;
+}
+
+@media (max-width: 400px) {
+ h1 {
+ font-size: 1.2rem;
+ }
+}`,
+ js: "",
+ },
+];
+
+export const DEFAULT_STARTER = WEB_STARTERS[0];
+
+export function starterById(id: string | null | undefined): WebStarter | undefined {
+ return WEB_STARTERS.find((starter) => starter.id === id);
+}
diff --git a/src/lib/quizzes/html-css.ts b/src/lib/quizzes/html-css.ts
index 17f1ee28..8949191a 100644
--- a/src/lib/quizzes/html-css.ts
+++ b/src/lib/quizzes/html-css.ts
@@ -892,7 +892,7 @@ export const QUIZZES: Record
{title}
-
- {AI_TOOLS.map((tool, i) => (
-
+ {START_STEPS.map((step, i) => {
+ const internal = step.cta.href.startsWith("/");
+ const cta = (
+ <>
+ {step.cta.label}
+
+ >
+ );
+ return (
+
- {/* Prompts */}
-
+ Step {i + 1}:
+ {step.title}
+
+
- {PROMPT_TEMPLATES.map((item, i) => (
-
+ {item.title}
-
- {item.prompt}
-
-
- {WORKFLOW_STEPS.map((step, i) => (
-
- Step {i + 1}:
- {step.title}
+
+ {group.title}
-
+ {group.tools.map((tool) => (
+
+ {tool.name}
+
- {SAFETY_RULES.map((rule, i) => (
-
+ {rule.title}
-
+
+ Do
+
+
+ {DOS.map((item) => (
+
+
+
+ Don’t
+
+
+ {DONTS.map((item) => (
+
+
- {GLOSSARY.map((entry) => (
-
-
+ {GLOSSARY.map((entry) => (
+
+ Ready to build something?
+
+
+ {goal.parts.map((part, i) => {
+ if (typeof part === "string") return part;
+ const filled = valueOf(values, goal, part.field);
+ return filled ? (
+ {filled}
+ ) : (
+
+ {blankFor(goal, part.field)}
+
+ );
+ })}
+ {beginner && BEGINNER_NOTE}
+
+
{hasProgress ? "Continue learning" : "Good places to start"}
-
- Finish the previous chapter first
+ One chapter at a time