Skip to content

Commit acdcb21

Browse files
Adutchguyclaude
andcommitted
Add Modules 9-10 (13 lessons), capstone, fast-track page, 49 placement and 79 review questions
Content - Module 9 Pythonic Python: iterators, generators, comprehension patterns, decorators, functools, type hints, async basics (async is local-only) - Module 10 Testing & Quality: pytest (learner writes tests that must catch mutants), fixtures & parametrize, readable code & linting, Git basics, packaging, and the wordkit capstone (fixtures, Git and capstone are local-only) - Placement bank: 37 -> 49 questions; review bank: 60 -> 79 questions - Regenerated exercises/ (72 lessons) Fast track for programmers - New /fast-track/ page: 18 verified "what is different in Python" rows - One button marks 20 lessons as skipped (orientation lesson never skipped) - content/fast-track/path.json, validated by tools/fasttrack.py (lesson ids exist, examples run and print the stated output) - Home page: "I already code in another language" button; "Fast track" nav link Tools and tests - tools/fasttrack.py + tools/tests/test_fasttrack.py (7 tests) - validate_content.py also validates the fast-track - content.py: placement, review, fast-track excluded from lesson discovery Docs - README, PLAN.md (M5 built, new counts) and CONTENT-STYLE-GUIDE.md (tests-of-tests, local_only rules, linecache style checks) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011MbSyzBx5szJ5JsA5STL4p
1 parent 7e9faf4 commit acdcb21

109 files changed

Lines changed: 6171 additions & 25 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ A free, open-source way to learn Python quickly and thoroughly, with **no sign-u
77

88
Both tracks come from the same lesson files, so they always match.
99

10-
> **Status:** early but usable. 59 lessons are written, from Start Here through Errors & Debugging, Modules & Tooling and Object-Oriented Programming, with four projects (a number-guessing game, a quiz engine, an expense tracker and a bank system). There is a placement test that suggests where to start and a spaced-review queue that brings finished lessons back at growing gaps. More modules are being added; see [docs/PLAN.md](docs/PLAN.md) for the full roadmap.
10+
> **Status:** early but usable. 72 lessons are written, from Start Here through Pythonic Python (iterators, generators, decorators, `functools`, type hints, async) and Testing & Quality (pytest, fixtures, linting, Git, packaging), with five projects: a number-guessing game, a quiz engine, an expense tracker, a bank system and a capstone where you build, test and publish a small package. There is a placement test that suggests where to start, a [fast track](web/src/pages/fast-track.astro) for people who already code in another language (it skips the lessons you do not need), and a spaced-review queue that brings finished lessons back at growing gaps. Optional tracks and polish are next; see [docs/PLAN.md](docs/PLAN.md) for the full roadmap.
1111
1212
## How learning works here
1313

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
---
2+
title: "Iterators and Iterables: How for Loops Really Work"
3+
minutes: 15
4+
prereqs: ["08-oop/03-dunder-methods"]
5+
concepts: ["iterable", "iterator", "iter()", "next()", "StopIteration", "__iter__", "__next__"]
6+
local_only: false
7+
hints:
8+
- "Countdown keeps the next number to hand out in self.current. __iter__ just returns self. __next__ raises StopIteration when self.current is 0 or less."
9+
- "In __next__: save value = self.current, then subtract 1 from self.current, then return value. Order matters: return the old value, not the new one."
10+
- "first_n: iterator = iter(iterable), then loop while len(items) < n: append next(iterator), and catch StopIteration with try/except to stop early. Checking the length BEFORE calling next means you never pull one item too many."
11+
---
12+
13+
## Why this matters
14+
15+
Every `for` loop in Python uses one small protocol. Once you know it, you understand why lists, files, dictionaries and `range` all work in a `for` loop, and you can make your own classes loopable.
16+
17+
## The idea
18+
19+
An **iterable** is anything you can loop over (a list, a string, a file). An **iterator** is the object that hands out the items one at a time. `iter()` turns an iterable into an iterator, and `next()` asks for the next item:
20+
21+
```python
22+
letters = iter("abc")
23+
print(next(letters)) # a
24+
print(next(letters)) # b
25+
print(next(letters)) # c
26+
print(next(letters)) # raises StopIteration: nothing left
27+
```
28+
29+
A `for` loop is just a `while` loop that calls `next()` and quietly stops when it sees `StopIteration`. To make your own iterator, write a class with two methods:
30+
31+
```python
32+
class Evens:
33+
def __init__(self, limit):
34+
self.n = 0
35+
self.limit = limit
36+
37+
def __iter__(self): # a loop asks for the iterator...
38+
return self # ...and this object is its own iterator
39+
40+
def __next__(self): # ...then calls this again and again
41+
if self.n >= self.limit:
42+
raise StopIteration # "I am finished"
43+
self.n += 2
44+
return self.n - 2
45+
46+
print(list(Evens(7))) # [0, 2, 4, 6]
47+
```
48+
49+
An iterator is **used up** after one pass. Looping over it a second time gives nothing.
50+
51+
## Try it
52+
53+
Run the example, then change `Evens(7)` to `Evens(0)`. What does `list()` give?
54+
55+
## Your turn
56+
57+
1. Write a class `Countdown(start)` that counts down to 1: `list(Countdown(3))` is `[3, 2, 1]`, and `list(Countdown(0))` is `[]`.
58+
2. Write a function `first_n(iterable, n)` that returns a list of the first `n` items of any iterable. If there are fewer than `n` items, return what exists. It must work on **endless** iterables, and it must not take more than `n` items from the iterator.
59+
60+
## Recap
61+
62+
- An iterable can give you an iterator with `iter()`; `next()` returns the next item.
63+
- `StopIteration` means "no more items". A `for` loop handles it for you.
64+
- Your own iterator class needs `__iter__` (return `self`) and `__next__`.
65+
- Iterators are used up after one pass.
66+
67+
## Common mistakes
68+
69+
- **Forgetting to raise `StopIteration`**, which makes the loop run forever.
70+
- **Returning the updated value** instead of the one you just handed out.
71+
- **Looping over the same iterator twice** and wondering why the second loop is empty.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Countdown:
2+
def __init__(self, start):
3+
self.current = start
4+
5+
def __iter__(self):
6+
return self
7+
8+
def __next__(self):
9+
if self.current <= 0:
10+
raise StopIteration
11+
value = self.current
12+
self.current -= 1
13+
return value
14+
15+
16+
def first_n(iterable, n):
17+
iterator = iter(iterable)
18+
items = []
19+
while len(items) < n:
20+
try:
21+
items.append(next(iterator))
22+
except StopIteration:
23+
break
24+
return items
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Write a class: Countdown(start) -> yields start, start-1, ..., 1
2+
# Write a function: first_n(iterable, n) -> list of the first n items
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
def _fn(name):
2+
import exercise
3+
4+
assert hasattr(exercise, name), f"Your program needs a function called {name}(). Define it with: def {name}(...):"
5+
func = getattr(exercise, name)
6+
assert callable(func), f"{name} should be a function, but it is {func!r}."
7+
return func
8+
9+
10+
def _cls(name):
11+
import exercise
12+
13+
assert hasattr(exercise, name), f"Your program needs a class called {name}. Start it with: class {name}:"
14+
cls = getattr(exercise, name)
15+
assert isinstance(cls, type), f"{name} should be a class, but it is {cls!r}."
16+
return cls
17+
18+
19+
import itertools
20+
21+
22+
def test_countdown_counts_down():
23+
Countdown = _cls("Countdown")
24+
assert list(Countdown(3)) == [3, 2, 1], f"list(Countdown(3)) should be [3, 2, 1], got {list(Countdown(3))!r}"
25+
assert list(Countdown(1)) == [1], "Countdown(1) should give just [1]"
26+
assert list(Countdown(0)) == [], "Countdown(0) should give an empty list"
27+
28+
29+
def test_countdown_works_in_a_for_loop_and_is_used_up():
30+
Countdown = _cls("Countdown")
31+
seen = []
32+
for number in Countdown(2):
33+
seen.append(number)
34+
assert seen == [2, 1], f"A for loop over Countdown(2) should see [2, 1], saw {seen!r}"
35+
counter = Countdown(2)
36+
list(counter)
37+
assert list(counter) == [], "An iterator is used up after one pass, so a second list() should be empty"
38+
39+
40+
def test_countdown_is_its_own_iterator():
41+
Countdown = _cls("Countdown")
42+
counter = Countdown(2)
43+
assert iter(counter) is counter, "__iter__ should return self"
44+
assert next(counter) == 2, "the first next() should give the start value"
45+
46+
47+
def test_first_n_basic():
48+
first_n = _fn("first_n")
49+
assert first_n([10, 20, 30, 40], 2) == [10, 20], f"first_n([10, 20, 30, 40], 2) should be [10, 20], got {first_n([10, 20, 30, 40], 2)!r}"
50+
assert first_n("abc", 3) == ["a", "b", "c"], "first_n should work on strings and give a list"
51+
assert first_n([1, 2], 5) == [1, 2], "with fewer items than n, return the items that exist"
52+
assert first_n([1, 2], 0) == [], "n of 0 should give an empty list"
53+
54+
55+
def test_first_n_works_on_endless_iterables():
56+
first_n = _fn("first_n")
57+
result = first_n(itertools.count(5), 3)
58+
assert result == [5, 6, 7], f"first_n(itertools.count(5), 3) should be [5, 6, 7], got {result!r}"
59+
60+
61+
def test_first_n_does_not_take_too_many():
62+
first_n = _fn("first_n")
63+
source = iter(range(10))
64+
assert first_n(source, 3) == [0, 1, 2], "the first three items should be 0, 1, 2"
65+
assert next(source) == 3, "first_n took more than n items from the iterator: the next unread item should be 3"
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
---
2+
title: "Generators: Producing Values One at a Time"
3+
minutes: 18
4+
prereqs: ["09-pythonic-python/01-iterators-and-iterables"]
5+
concepts: ["generator", "yield", "lazy evaluation", "infinite sequences", "memory"]
6+
local_only: false
7+
hints:
8+
- "A generator function uses yield instead of return. fibonacci: set a, b = 0, 1, then in an endless while True loop yield a and update with a, b = b, a + b."
9+
- "chunks: raise ValueError(\"size must be at least 1\") when size < 1, then loop for start in range(0, len(items), size) and yield items[start:start + size]. Slices past the end are just shorter, which handles the last chunk."
10+
- "running_total: keep total = 0, then for number in numbers: total += number and yield total. Do NOT build a list first: yield each total as soon as you have it."
11+
---
12+
13+
## Why this matters
14+
15+
Writing an iterator class works, but it is a lot of ceremony. A **generator** is a function that produces its values one at a time, and Python builds the iterator for you. Generators let you work with huge or even endless sequences using almost no memory.
16+
17+
## The idea
18+
19+
Put `yield` in a function and it becomes a generator function. Calling it does not run the body; it gives you a generator object. Each `next()` runs the body up to the next `yield`, hands that value out, and **pauses** right there:
20+
21+
```python
22+
def count_up(limit):
23+
n = 1
24+
while n <= limit:
25+
yield n # hand out n, then pause here
26+
n += 1 # resumes here on the next request
27+
28+
for n in count_up(3):
29+
print(n) # 1, 2, 3
30+
```
31+
32+
Because values are made on demand (**lazily**), a generator can describe an endless sequence:
33+
34+
```python
35+
def naturals():
36+
n = 1
37+
while True:
38+
yield n
39+
n += 1
40+
```
41+
42+
You must not call `list(naturals())`, which would never finish. Take a few with a loop and `break`, or with `itertools.islice(naturals(), 5)`.
43+
44+
A generator is an iterator, so it is used up after one pass, just like in the last lesson.
45+
46+
## Try it
47+
48+
Run `count_up`, then call `gen = count_up(2)` and `next(gen)` three times by hand. What happens on the third call?
49+
50+
## Your turn
51+
52+
Write three generator functions:
53+
54+
- `fibonacci()` yields `0, 1, 1, 2, 3, 5, ...` forever.
55+
- `chunks(items, size)` yields lists of `size` items from `items`; the last one may be shorter. If `size` is less than 1, raise `ValueError`. (A generator raises when the first value is requested.)
56+
- `running_total(numbers)` yields the running total: `[1, 2, 3]` gives `1, 3, 6`. It must be lazy: it may only read an item from `numbers` when asked for the next value.
57+
58+
## Recap
59+
60+
- `yield` makes a function a generator; each value is produced on demand.
61+
- A generator pauses at `yield` and resumes where it left off.
62+
- Generators can be endless, and they use very little memory.
63+
- Use `itertools.islice` to take part of an endless generator.
64+
65+
## Common mistakes
66+
67+
- **Using `return` with a list** when the whole point is to avoid building one.
68+
- **Calling `list()` on an endless generator**, which never finishes.
69+
- **Reusing a used-up generator**: call the generator function again for a fresh one.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def fibonacci():
2+
a, b = 0, 1
3+
while True:
4+
yield a
5+
a, b = b, a + b
6+
7+
8+
def chunks(items, size):
9+
if size < 1:
10+
raise ValueError("size must be at least 1")
11+
for start in range(0, len(items), size):
12+
yield items[start:start + size]
13+
14+
15+
def running_total(numbers):
16+
total = 0
17+
for number in numbers:
18+
total += number
19+
yield total
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Write three generator functions:
2+
#
3+
# fibonacci() -> yields 0, 1, 1, 2, 3, 5, ... forever
4+
# chunks(items, size) -> yields lists of `size` items (last may be shorter)
5+
# running_total(numbers) -> yields the running total, lazily
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
def _fn(name):
2+
import exercise
3+
4+
assert hasattr(exercise, name), f"Your program needs a function called {name}(). Define it with: def {name}(...):"
5+
func = getattr(exercise, name)
6+
assert callable(func), f"{name} should be a function, but it is {func!r}."
7+
return func
8+
9+
10+
import inspect
11+
import itertools
12+
13+
import pytest
14+
15+
16+
def test_fibonacci_is_an_endless_generator():
17+
fibonacci = _fn("fibonacci")
18+
gen = fibonacci()
19+
assert inspect.isgenerator(gen), "fibonacci() should return a generator: use yield inside the function"
20+
first = list(itertools.islice(gen, 10))
21+
assert first == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34], f"The first ten Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, got {first!r}"
22+
23+
24+
def test_fibonacci_gives_a_fresh_sequence_each_call():
25+
fibonacci = _fn("fibonacci")
26+
a = fibonacci()
27+
next(a)
28+
next(a)
29+
assert next(fibonacci()) == 0, "each call to fibonacci() should start again from 0"
30+
31+
32+
def test_chunks():
33+
chunks = _fn("chunks")
34+
assert list(chunks([1, 2, 3, 4, 5], 2)) == [[1, 2], [3, 4], [5]], f"chunks([1, 2, 3, 4, 5], 2) should be [[1, 2], [3, 4], [5]], got {list(chunks([1, 2, 3, 4, 5], 2))!r}"
35+
assert list(chunks([1, 2, 3], 3)) == [[1, 2, 3]], "a size equal to the length gives one chunk"
36+
assert list(chunks([], 4)) == [], "no items means no chunks"
37+
assert list(chunks("abcd", 3)) == ["abc", "d"], "slices of a string are strings, so chunks should keep the type of the slices"
38+
39+
40+
def test_chunks_is_a_generator_and_validates_size():
41+
chunks = _fn("chunks")
42+
assert inspect.isgenerator(chunks([1], 1)), "chunks should be a generator function (use yield)"
43+
with pytest.raises(ValueError):
44+
list(chunks([1, 2], 0))
45+
46+
47+
def test_running_total():
48+
running_total = _fn("running_total")
49+
assert list(running_total([1, 2, 3])) == [1, 3, 6], f"running_total([1, 2, 3]) should give 1, 3, 6, got {list(running_total([1, 2, 3]))!r}"
50+
assert list(running_total([])) == [], "no numbers means no totals"
51+
assert list(running_total([5, -5, 5])) == [5, 0, 5], "negative numbers should work too"
52+
53+
54+
def test_running_total_is_lazy():
55+
running_total = _fn("running_total")
56+
pulled = []
57+
58+
def source():
59+
for n in (1, 2, 3, 4):
60+
pulled.append(n)
61+
yield n
62+
63+
gen = running_total(source())
64+
assert inspect.isgenerator(gen), "running_total should be a generator function (use yield)"
65+
assert pulled == [], "creating the generator must not read anything yet"
66+
assert next(gen) == 1, "the first total should be 1"
67+
assert pulled == [1], f"after one next() only one item should have been read, but {pulled!r} were read: yield each total as soon as you have it"

0 commit comments

Comments
 (0)