How Course Scripts Work
Every practical lesson gives you complete Python scripts. Each one appears with
its file name, in a sentence such as "Save this as readiness.py". You create
a file with that name in the exercise folder, paste the whole script into it
and save it. Then, in a terminal where the course environment is active, you
run it from the same folder:
python readiness.py
Python reads the file from top to bottom and runs each line in turn. The script prints its results in the terminal and, where a lesson needs a chart, saves the chart as an image file next to the script.
This lesson checks that you can read such a script well enough to predict what it does, change it, and find a problem from an error message. Those three skills are what the rest of the course relies on.
Predict Before You Run
Before running a script, read it and write down what you expect it to print. Then run it and compare. When your prediction matches, you know you read the code correctly. When it does not, the difference shows you exactly which line you misunderstood, which is far more useful than a script that simply "worked". The exercises in this course ask for predictions often, for that reason.
Reading an Error Message
When Python meets a line it cannot run, it stops and prints an error message, called a traceback:
Traceback (most recent call last):
File "~/ai-practice/script-readiness/readiness.py", line 12, in <module>
if score >= threshold:
^^^^^^^^^^^^^^^^^^
TypeError: '>=' not supported between instances of 'int' and 'str'
This is illustrative output; the folder path in the second line will be your own.

Read it from the bottom up, as the diagram shows. The last line says what
happened: first the error type, here TypeError, then a description. The
lines above say where: the file, the line number and the code on that line,
with ^ characters under the part that failed. In longer tracebacks the last
File line is usually the one in your own script that matters.
Two error types appear in this lesson:
TypeError: an operation was used with values it cannot handle, such as comparing a number with text.NameError: the script used a name that was never created, often because of a typing mistake. Python may suggest the name you meant.
Charts Are Saved as Files
Matplotlib can either open a window to show a chart or draw it straight into a
file. Course scripts choose the file route with matplotlib.use("Agg"): Agg
is a drawing engine that writes images without opening a window, so the
scripts behave the same on every computer, including ones where a window would
not appear. Each script also prints the numbers the chart shows, so you never
need to look at an image to check a result.
Exercise: Run, Adapt and Repair a Script
Starting state: the course environment from the setup lesson, active in
your terminal: the prompt starts with (.venv).
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/ai-practice/script-readiness cd ~/ai-practice/script-readinessWindows PowerShell:
mkdir $HOME\ai-practice\script-readiness cd $HOME\ai-practice\script-readinessSave this as
readiness.pyin that folder:"""Readiness check: predict what this script prints before you run it.""" import matplotlib matplotlib.use("Agg") # draw charts into files; no window opens import matplotlib.pyplot as plt scores = {"Ana": 7, "Ben": 4, "Chi": 9} threshold = 5 passed = [] for name, score in scores.items(): if score >= threshold: passed.append(name) print("Passed:", passed) print("Pass rate:", round(len(passed) / len(scores) * 100), "%") fig, ax = plt.subplots() ax.bar(list(scores), list(scores.values())) ax.axhline(threshold, linestyle="--", color="black") ax.set_xlabel("Learner") ax.set_ylabel("Score") fig.savefig("scores.png") print("Saved scores.png") -
Before running it, write down the two lines you expect it to print after
Passed:andPass rate:. Then run it and list the folder:python readiness.py lsOutput:
Passed: ['Ana', 'Chi'] Pass rate: 67 % Saved scores.pnglsnow showsscores.pngbeside the script. Open it in any image viewer if you like: three bars with a dashed line at 5.
How the Script Works
scores is a dictionary that maps each learner's name to a score.
scores.items() gives the pairs one at a time, so the for loop sees
("Ana", 7), then ("Ben", 4), then ("Chi", 9). The if keeps the names
whose score is at least threshold; Ben's 4 is below 5, so passed ends up
as ['Ana', 'Chi'].
The pass rate divides the two passes by the three learners, multiplies by 100
to get a percentage, 66.67, and round turns it into the whole number 67.
print separates its values with spaces, which is why a space appears before
%.
The chart lines create a figure (fig) with one set of axes (ax), draw one
bar per learner, add a dashed horizontal line at the threshold, label both
axes and write the result to scores.png. Because the drawing engine was set
to Agg before pyplot was imported, no window opens.
-
Change a value. In your editor, change
threshold = 5tothreshold = 8, save, predict the new output and run the script again. It prints:Passed: ['Chi'] Pass rate: 33 % Saved scores.pngOnly Chi's 9 reaches 8, and one of three learners is 33%. Changing one value and predicting its effect is how you will explore every model in the course.
-
Cause an error on purpose. Change the line to
threshold = "8", with quotation marks, save and run it. The script stops with theTypeErrorshown earlier in this lesson, reported at line 12, theifline. The quotation marks make"8"a piece of text, and Python cannot decide whether the number 7 is greater than a piece of text. Remove the quotation marks, save, and run once more to confirm that it works again.
Success: your prediction in step 2 matched, or you can explain the
difference; step 3 printed ['Chi'] and 33 %; you can point to the line
and error type in step 4's message; and scores.png exists.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
ModuleNotFoundError: No module named 'matplotlib' | The course environment is not active | Activate it as in the setup lesson and rerun |
can't open file or No such file or directory mentioning readiness.py | The terminal is in another folder, or the file was saved elsewhere or under another name | Run pwd and ls; move to the exercise folder or save the file there |
IndentationError | Spaces at the start of some lines were lost while pasting | Paste the whole script again, keeping the indentation |
The output still shows ['Ana', 'Chi'] after step 3 | The edited file was not saved | Save in your editor, then rerun |
-
Clean up. macOS and Linux:
cd ~/ai-practice ls rm -rf script-readiness lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse script-readiness lsCheck that the first
lsshowsscript-readinessbefore removing it. Do the independent task first if you want to keep working in this folder.
Independent task: in the exercise folder, save this as broken.py, run
it, and fix it using only the error message:
"""Find and fix the problem using only the error message."""
prices = [4.50, 2.25, 3.00]
total = 0
for price in prices:
total = total + price
average = totl / len(prices)
print("Average price:", round(average, 2))
Check Your Understanding
A learner runs a course script and sees:
Traceback (most recent call last):
File "~/ai-practice/inspect-wine/inspect_wine.py", line 12, in <module>
orders = pd.read_csv("orders.csv")
FileNotFoundError: [Errno 2] No such file or directory: 'orders.csv'
- What went wrong, according to the last line?
- Which line of their script should they look at?
- Name two different causes that would produce this message.
Answer and Reasoning
Independent task
The script stops with:
NameError: name 'totl' is not defined. Did you mean: 'total'?
on line 6. The variable created on line 3 is total, and line 6 misspells it
as totl. Change line 6 to average = total / len(prices) and run again. It
prints Average price: 3.25, because the three prices add up to 9.75 and
9.75 divided by 3 is 3.25.
Understanding check
- A
FileNotFoundError: Python could not find a file namedorders.csv. - Line 12, the
pd.read_csv("orders.csv")line ofinspect_wine.py. - The script was run from a different folder, so Python looked for
orders.csvin the wrong place; or the file was never saved, was saved in another folder, or was saved under a different name. Checking withpwdandlstells you which.