Skip to content

Commit 0961d3a

Browse files
committed
Add Modules 6-8 (21 lessons), expense-tracker and bank projects, learn CLI
- Module 6 Errors & Debugging (6): try/except, raising, debugging, logging, context managers, project: expense tracker - Module 7 Modules & Tooling (6): imports, collections, dates, itertools and random, pip/venv (local-only), project layout - Module 8 OOP (9): classes, methods, dunder methods, inheritance, composition, dataclasses, properties, ABCs/protocols, project: bank system - Add `python -m learn` (next, check, hint, status, list) with saved progress - Placement test grows to 37 questions; review queue to 60 - Regenerate exercises/ (59 lessons); update README, PLAN, style guide
1 parent 0928679 commit 0961d3a

163 files changed

Lines changed: 8510 additions & 17 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.

‎.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,7 @@ Thumbs.db
1919

2020
# Learner scratch space (used by the future `learn` CLI)
2121
workspace/
22+
23+
# Local-track progress written by `python -m learn`
24+
.learn-progress.json
25+
.learn-progress.json.tmp

‎README.md‎

Lines changed: 15 additions & 2 deletions
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. 38 lessons are written: Start Here, Foundations, Control Flow, Data Structures, Functions and Text & Files, with two projects (a number-guessing game and a quiz engine). 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. 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.
1111
1212
## How learning works here
1313

@@ -39,7 +39,19 @@ exercises/01-foundations/01-hello-world/
3939
└── test_exercise.py <- the checks (read-only)
4040
```
4141

42-
Check your work from the repository root:
42+
The `learn` helper keeps track of where you are, so you never have to hunt for the next lesson. Run it from the repository root:
43+
44+
```bash
45+
python -m learn # what to do next
46+
python -m learn check # run the checks for your current lesson (a pass marks it complete)
47+
python -m learn hint # reveal one hint at a time
48+
python -m learn status # your progress, module by module
49+
python -m learn list # every lesson, with the finished ones ticked
50+
```
51+
52+
`check` and `hint` also accept a lesson number from `list`, or a word from its name (`python -m learn check variables`). Your progress is saved in `.learn-progress.json`, which Git ignores.
53+
54+
Prefer plain pytest? That works too:
4355

4456
```bash
4557
pytest exercises/01-foundations/01-hello-world
@@ -54,6 +66,7 @@ Tip: work on your own branch (`git switch -c my-answers`) or in a fork, so your
5466
| `content/` | **Source of truth.** One folder per lesson: `lesson.md`, `starter.py`, `solution.py`, `test_exercise.py`. Also `placement/questions.json` (placement-test questions) and `review/questions.json` (spaced-review questions) |
5567
| `exercises/` | Local track, **generated** from `content/` (do not edit by hand, except `conftest.py`) |
5668
| `web/` | The website (Astro) and the in-browser Python runner (Pyodide) |
69+
| `learn/` | The `python -m learn` command-line guide for the local track |
5770
| `tools/` | Python scripts that validate lessons and generate `exercises/` |
5871
| `docs/` | Plan, content style guide |
5972

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
---
2+
title: "Catching Errors with try and except"
3+
minutes: 15
4+
prereqs: ["05-text-and-files/06-regular-expressions"]
5+
concepts: ["try", "except", "exception", "ValueError", "ZeroDivisionError", "KeyError", "else", "finally"]
6+
local_only: false
7+
hints:
8+
- "to_int: put int(text) inside a try block and return it. Under except ValueError: return default. Only ValueError, not every possible error."
9+
- "safe_divide: try: return a / b, then except ZeroDivisionError: return None."
10+
- "get_age: the try block is return int(person[\"age\"]). Add except KeyError: return \"unknown\" and a second clause except (ValueError, TypeError): return \"invalid\". A tuple lets one clause catch several kinds of error."
11+
---
12+
13+
## Why this matters
14+
15+
So far an error has meant a crash. Real programs meet bad input, missing files and surprises all the time, and a good program decides what to do about them instead of dying. Python lets you **catch** an error and carry on.
16+
17+
## The idea
18+
19+
```python
20+
text = "abc"
21+
try:
22+
number = int(text) # Python tries this...
23+
except ValueError: # ...and if a ValueError happens, jumps here
24+
number = 0
25+
print(number) # 0
26+
```
27+
28+
Name the **kind** of error you expect. Catching too much hides real bugs. A few more parts:
29+
30+
```python
31+
try:
32+
price = float(text)
33+
except ValueError as err: # "as err" keeps the error so you can show it
34+
print("Not a number:", err)
35+
else: # runs only if nothing went wrong
36+
print("Price is", price)
37+
finally: # always runs, error or not
38+
print("done")
39+
```
40+
41+
One clause can catch several kinds: `except (ValueError, TypeError):`.
42+
43+
## Try it
44+
45+
Run the example with `text = "4.5"`, then `"abc"`, then `""`. Which of `else` and `finally` ran each time? Then try `int(None)` inside the try: that is a `TypeError`, so the `except ValueError` clause does **not** catch it.
46+
47+
## Your turn
48+
49+
Write three functions:
50+
51+
- `to_int(text, default=0)`: return `int(text)`, or `default` if the text is not a whole number. Anything that is not a `ValueError` should still crash (for example `to_int(None)` raises a `TypeError`).
52+
- `safe_divide(a, b)`: return `a / b`, or `None` when `b` is zero.
53+
- `get_age(person)`: `person` is a dictionary. Return `int(person["age"])`. If there is no `"age"` key return `"unknown"`. If the value cannot be turned into a whole number (text like `"abc"`, or `None`) return `"invalid"`.
54+
55+
## Recap
56+
57+
- `try` runs code that might fail; `except SomeError` handles that one kind of failure.
58+
- Catch the specific errors you expect so real bugs still show up.
59+
- `else` runs when nothing failed; `finally` always runs.
60+
61+
## Common mistakes
62+
63+
- **A bare `except:` that catches everything.** It even hides typos (`NameError`). Name the error.
64+
- **Putting too much inside `try`.** Keep it to the lines that can actually fail.
65+
- **Forgetting the colon or indentation** after `try:` / `except ...:`, which gives a `SyntaxError` or `IndentationError`.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
def to_int(text, default=0):
2+
try:
3+
return int(text)
4+
except ValueError:
5+
return default
6+
7+
8+
def safe_divide(a, b):
9+
try:
10+
return a / b
11+
except ZeroDivisionError:
12+
return None
13+
14+
15+
def get_age(person):
16+
try:
17+
return int(person["age"])
18+
except KeyError:
19+
return "unknown"
20+
except (ValueError, TypeError):
21+
return "invalid"
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Write three functions that RETURN their answers:
2+
#
3+
# def to_int(text, default=0): ... to_int("42") -> 42 to_int("abc") -> 0 to_int("x", default=-1) -> -1
4+
# def safe_divide(a, b): ... safe_divide(10, 4) -> 2.5 safe_divide(1, 0) -> None
5+
# def get_age(person): ... get_age({"age": "42"}) -> 42
6+
# get_age({}) -> "unknown" get_age({"age": "abc"}) -> "invalid"
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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 test_to_int_converts_valid_text():
11+
to_int = _fn("to_int")
12+
assert to_int("42") == 42, f"to_int('42') should return 42 but returned {to_int('42')!r}."
13+
assert to_int(" 7 ") == 7, f"to_int(' 7 ') should return 7 (int() ignores spaces) but returned {to_int(' 7 ')!r}."
14+
15+
16+
def test_to_int_uses_the_default_for_bad_text():
17+
to_int = _fn("to_int")
18+
for text in ["abc", "", "3.5"]:
19+
assert to_int(text) == 0, f"to_int({text!r}) should return the default 0 but returned {to_int(text)!r}."
20+
assert to_int("x", default=-1) == -1, "to_int('x', default=-1) should return -1."
21+
assert to_int("x", -5) == -5, "to_int('x', -5) should return -5: the default can be given by position too."
22+
23+
24+
def test_to_int_only_catches_value_errors():
25+
import pytest
26+
27+
to_int = _fn("to_int")
28+
with pytest.raises(TypeError):
29+
to_int(None)
30+
31+
32+
def test_safe_divide():
33+
safe_divide = _fn("safe_divide")
34+
assert safe_divide(10, 4) == 2.5, f"safe_divide(10, 4) should be 2.5 but was {safe_divide(10, 4)!r}."
35+
assert safe_divide(0, 5) == 0, "safe_divide(0, 5) should be 0."
36+
assert safe_divide(1, 0) is None, f"safe_divide(1, 0) should return None but returned {safe_divide(1, 0)!r}."
37+
38+
39+
def test_get_age_valid_and_missing():
40+
get_age = _fn("get_age")
41+
assert get_age({"age": "42"}) == 42, f"get_age({{'age': '42'}}) should return 42 but returned {get_age({'age': '42'})!r}."
42+
assert get_age({"name": "Ada"}) == "unknown", "A dictionary with no 'age' key should give 'unknown'."
43+
44+
45+
def test_get_age_invalid_values():
46+
get_age = _fn("get_age")
47+
assert get_age({"age": "abc"}) == "invalid", "get_age({'age': 'abc'}) should give 'invalid' (ValueError)."
48+
assert get_age({"age": None}) == "invalid", "get_age({'age': None}) should give 'invalid' (int(None) raises TypeError, which you must catch too)."
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
---
2+
title: "Raising Your Own Exceptions"
3+
minutes: 18
4+
prereqs: ["06-errors-and-debugging/01-try-and-except"]
5+
concepts: ["raise", "ValueError", "TypeError", "custom exception", "error message", "validation"]
6+
local_only: false
7+
hints:
8+
- "validate_age: first check the type with isinstance(age, int) and raise TypeError(\"age must be a whole number\"). Then check the range and raise ValueError(\"age must be between 0 and 150\"). Return age at the end."
9+
- "OutOfStock is a one-line class: class OutOfStock(Exception): pass. In take, look up have = stock.get(item, 0); if have < quantity: raise OutOfStock(f\"only {have} {item} left, wanted {quantity}\"). Otherwise subtract and return the new count."
10+
- "parse_percent: if not text.endswith(\"%\"), raise ValueError(f\"not a percentage: {text!r}\"). Convert text[:-1] with int() inside try/except ValueError and raise the same ValueError message from the except block. Finally check 0 <= value <= 100."
11+
---
12+
13+
## Why this matters
14+
15+
Catching errors is half the story. The other half is **raising** them yourself: when a function is given something it cannot work with, stopping loudly with a clear message is better than quietly returning nonsense.
16+
17+
## The idea
18+
19+
```python
20+
def set_volume(level):
21+
if not 0 <= level <= 10:
22+
raise ValueError(f"volume must be 0-10, got {level}")
23+
return level
24+
```
25+
26+
Pick the built-in error that fits: `ValueError` (right type, bad value), `TypeError` (wrong type), `KeyError`, `IndexError`... A good message says what was wrong **and what was received**.
27+
28+
You can also define an error for your own program. Treat these two lines as a recipe for now (Module 8 explains classes):
29+
30+
```python
31+
class OutOfStock(Exception):
32+
pass
33+
```
34+
35+
Then `raise OutOfStock("no apples left")` works, and callers can write `except OutOfStock:`. A bare `raise` inside an `except` block re-raises the error you just caught.
36+
37+
## Try it
38+
39+
Call `set_volume(11)` without a `try` and read the traceback. Then wrap the call in `try`/`except ValueError as err` and print `err`.
40+
41+
## Your turn
42+
43+
Write:
44+
45+
- `validate_age(age)`: raise `TypeError("age must be a whole number")` if `age` is not an `int`; raise `ValueError("age must be between 0 and 150")` if it is outside 0 to 150; otherwise return `age`.
46+
- A custom error `OutOfStock` (a subclass of `Exception`).
47+
- `take(stock, item, quantity=1)`: `stock` is a dictionary of item to count. If there are fewer than `quantity`, raise `OutOfStock` with the message `only 2 apple left, wanted 5` (the real numbers and name). Otherwise subtract `quantity` and return the new count.
48+
- `parse_percent(text)`: turn `"45%"` into `45`. A text without a trailing `%` or with a non-whole number before it raises `ValueError("not a percentage: 'abc'")` (showing the text with `!r`). A value outside 0 to 100 raises `ValueError` whose message starts with `percentage out of range`.
49+
50+
## Recap
51+
52+
- `raise SomeError("message")` stops the function and hands the error to the caller.
53+
- Choose the closest built-in error, and say what was received in the message.
54+
- `class MyError(Exception): pass` creates an error type of your own.
55+
56+
## Common mistakes
57+
58+
- **Returning an error code instead of raising**, which callers forget to check.
59+
- **Vague messages** like `"invalid"`. Include the bad value.
60+
- **Raising a class that is not an exception**, which gives a `TypeError: exceptions must derive from BaseException`.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
def validate_age(age):
2+
if not isinstance(age, int):
3+
raise TypeError("age must be a whole number")
4+
if not 0 <= age <= 150:
5+
raise ValueError("age must be between 0 and 150")
6+
return age
7+
8+
9+
class OutOfStock(Exception):
10+
pass
11+
12+
13+
def take(stock, item, quantity=1):
14+
have = stock.get(item, 0)
15+
if have < quantity:
16+
raise OutOfStock(f"only {have} {item} left, wanted {quantity}")
17+
stock[item] = have - quantity
18+
return stock[item]
19+
20+
21+
def parse_percent(text):
22+
if not text.endswith("%"):
23+
raise ValueError(f"not a percentage: {text!r}")
24+
try:
25+
value = int(text[:-1])
26+
except ValueError:
27+
raise ValueError(f"not a percentage: {text!r}")
28+
if not 0 <= value <= 100:
29+
raise ValueError(f"percentage out of range: {value}")
30+
return value
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Write:
2+
#
3+
# def validate_age(age): ... raises TypeError / ValueError, otherwise returns age
4+
# class OutOfStock(Exception): ... your own error type
5+
# def take(stock, item, quantity=1): ... returns the new count, or raises OutOfStock
6+
# def parse_percent(text): ... parse_percent("45%") -> 45
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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 pytest
11+
12+
13+
def test_validate_age_accepts_good_values():
14+
validate_age = _fn("validate_age")
15+
for age in [0, 35, 150]:
16+
assert validate_age(age) == age, f"validate_age({age}) should return {age}."
17+
18+
19+
def test_validate_age_rejects_wrong_type():
20+
validate_age = _fn("validate_age")
21+
with pytest.raises(TypeError) as info:
22+
validate_age("35")
23+
assert "whole number" in str(info.value), f"The TypeError message should say the age must be a whole number, but it was {str(info.value)!r}."
24+
25+
26+
def test_validate_age_rejects_out_of_range():
27+
validate_age = _fn("validate_age")
28+
for age in [-1, 151]:
29+
with pytest.raises(ValueError) as info:
30+
validate_age(age)
31+
assert "between 0 and 150" in str(info.value), f"validate_age({age}) should raise ValueError('age must be between 0 and 150') but the message was {str(info.value)!r}."
32+
33+
34+
def test_out_of_stock_is_an_exception_type():
35+
import exercise
36+
37+
assert hasattr(exercise, "OutOfStock"), "Define your own error with: class OutOfStock(Exception):"
38+
assert isinstance(exercise.OutOfStock, type) and issubclass(exercise.OutOfStock, Exception), "OutOfStock must be a class that inherits from Exception: class OutOfStock(Exception):"
39+
40+
41+
def test_take_reduces_stock():
42+
take = _fn("take")
43+
stock = {"apple": 5}
44+
assert take(stock, "apple", 2) == 3, "take({'apple': 5}, 'apple', 2) should return 3."
45+
assert stock == {"apple": 3}, f"take should also update the dictionary, which is now {stock!r}."
46+
assert take(stock, "apple") == 2, "The quantity defaults to 1."
47+
48+
49+
def test_take_raises_out_of_stock_with_a_clear_message():
50+
import exercise
51+
52+
take = _fn("take")
53+
with pytest.raises(exercise.OutOfStock) as info:
54+
take({"apple": 2}, "apple", 5)
55+
assert str(info.value) == "only 2 apple left, wanted 5", f"The message should be 'only 2 apple left, wanted 5' but it was {str(info.value)!r}."
56+
with pytest.raises(exercise.OutOfStock):
57+
take({}, "pear")
58+
59+
60+
def test_parse_percent_valid():
61+
parse_percent = _fn("parse_percent")
62+
assert parse_percent("45%") == 45, f"parse_percent('45%') should return 45 but returned {parse_percent('45%')!r}."
63+
assert parse_percent("0%") == 0 and parse_percent("100%") == 100, "0% and 100% are both allowed."
64+
65+
66+
def test_parse_percent_malformed():
67+
parse_percent = _fn("parse_percent")
68+
for text in ["45", "abc%", "%", "4.5%"]:
69+
with pytest.raises(ValueError) as info:
70+
parse_percent(text)
71+
assert str(info.value) == f"not a percentage: {text!r}", f"parse_percent({text!r}) should raise ValueError('not a percentage: {text!r}') but the message was {str(info.value)!r}."
72+
73+
74+
def test_parse_percent_out_of_range():
75+
parse_percent = _fn("parse_percent")
76+
with pytest.raises(ValueError) as info:
77+
parse_percent("150%")
78+
assert str(info.value).startswith("percentage out of range"), f"parse_percent('150%') should raise a ValueError starting with 'percentage out of range' but the message was {str(info.value)!r}."

0 commit comments

Comments
 (0)