Add lesson 8: Errors and how to read them

Mira Kovac 1 year ago
parent 8b6437ddbc commit b8dc0c1ee78c75e55628da05156a458f1380435e
3 changed files with 42 additions and 0 deletions
+19-0lessons/08-errors-and-how-to-read-them/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 8: Errors and how to read them
2+
3+This lesson covers errors and how to read them. You'll read a short explanation, try three small exercises and finish with a quiz.
4+
5+Full lesson: [https://glibcode.net/courses/python-basics/lessons/8](https://glibcode.net/courses/python-basics/lessons/8)
6+
7+## Files
8+
9+- `errors.py`: reading a traceback and catching exceptions
10+
11+## Run it
12+
13+```sh
14+python3 errors.py
15+```
16+
17+## Exercises
18+
19+See [exercises.md](exercises.md). Ask in the forum once you've tried.
+18-0lessons/08-errors-and-how-to-read-them/errors.py ADDED
@@ -0,0 +1,18 @@
1+def average(numbers):
2+ return sum(numbers) / len(numbers)
3+
4+
5+try:
6+ print(average([4, 8, 15]))
7+ print(average([])) # ZeroDivisionError: read the last line of the traceback first
8+except ZeroDivisionError:
9+ print("Can't average an empty list")
10+
11+while True:
12+ raw = input("Enter a number: ")
13+ try:
14+ value = float(raw)
15+ break
16+ except ValueError:
17+ print(f"{raw!r} is not a number, try again")
18+print("Thanks,", value)
+5-0lessons/08-errors-and-how-to-read-them/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 8
2+
3+1. Time yourself: rewrite the example from memory in 10 minutes, then diff it against the original.
4+2. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to?
5+3. Add a check that prints a warning when a result looks wrong (negative, empty, too big).