Artificial Intelligence Fundamentals / Start Here

Run and adapt a course script

Lesson 3 of 26. Open to read. No account needed.

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.

A Python error message with its parts labelled: the first line announces a traceback; the File line names the script and line 12; the next line repeats the code on that line with carets under the part that failed; the last line gives the error type, TypeError, followed by a description of what went wrong.

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).

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/script-readiness
    cd ~/ai-practice/script-readiness
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\script-readiness
    cd $HOME\ai-practice\script-readiness
    

    Save this as readiness.py in 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")
    
  2. Before running it, write down the two lines you expect it to print after Passed: and Pass rate:. Then run it and list the folder:

    python readiness.py
    ls
    

    Output:

    Passed: ['Ana', 'Chi']
    Pass rate: 67 %
    Saved scores.png
    

    ls now shows scores.png beside 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.

  1. Change a value. In your editor, change threshold = 5 to threshold = 8, save, predict the new output and run the script again. It prints:

    Passed: ['Chi']
    Pass rate: 33 %
    Saved scores.png
    

    Only 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.

  2. Cause an error on purpose. Change the line to threshold = "8", with quotation marks, save and run it. The script stops with the TypeError shown earlier in this lesson, reported at line 12, the if line. 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 seeLikely causeNext step
ModuleNotFoundError: No module named 'matplotlib'The course environment is not activeActivate it as in the setup lesson and rerun
can't open file or No such file or directory mentioning readiness.pyThe terminal is in another folder, or the file was saved elsewhere or under another nameRun pwd and ls; move to the exercise folder or save the file there
IndentationErrorSpaces at the start of some lines were lost while pastingPaste the whole script again, keeping the indentation
The output still shows ['Ana', 'Chi'] after step 3The edited file was not savedSave in your editor, then rerun
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf script-readiness
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse script-readiness
    ls
    

    Check that the first ls shows script-readiness before 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'
  1. What went wrong, according to the last line?
  2. Which line of their script should they look at?
  3. 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

  1. A FileNotFoundError: Python could not find a file named orders.csv.
  2. Line 12, the pd.read_csv("orders.csv") line of inspect_wine.py.
  3. The script was run from a different folder, so Python looked for orders.csv in the wrong place; or the file was never saved, was saved in another folder, or was saved under a different name. Checking with pwd and ls tells you which.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy