Assignment: Python and NumPy Foundations

Python
Jupyter
NumPy
debugging
assignment
Learn the Jupyter workflow, basic Python, NumPy arrays, simple plots, documentation lookup, and evidence-based debugging before circuit linear algebra.

Where this fits

Complete Python First Steps in Jupyter before this lesson. This notebook assumes that you can run cells, use simple variables, recognize int, float, str, and bool, and select an item from a list. Complete this lesson before From Two Loops to a Matrix.

The sequence in this second notebook is:

run working code → change one value → use arrays → write a function → read documentation → repair an error → graph and check

Learning goals

  • I can distinguish Markdown cells from code cells and run a notebook in order.
  • I can use variables, arithmetic, lists, indexing, loops, and functions.
  • I can create a NumPy array and inspect its shape, type, values, and units.
  • I can apply one calculation to a complete array and verify the result.
  • I can make and interpret a labelled graph.
  • I can use help(), ?, official documentation, and an exact error message to repair code.
  • I can submit a notebook containing reproducible code, output, checks, and sources.

What to download

  1. Download Notebook 1: Python and NumPy Foundations.
  2. Click OPEN JUPYTERLITE NOW. This opens the browser program that runs the notebook; it is not another instruction page.
  3. In JupyterLite, click Upload Files, select 01-engineering-calculator.ipynb, and then double-click the uploaded notebook. Choose Python (Pyodide) if asked.
  4. Use the step-by-step JupyterLite instructions if you need help opening, editing, saving, or downloading the notebook. The local Jupyter installation pathway is the alternative for WSL, Windows, macOS, or Linux.
  5. Rename the file before working:
studentnumber-lastname-jupyter-foundations.ipynb

The notebook supplies working demonstrations, numbered TODO cells, a command sandbox, and an intentional error challenge. Complete them in order rather than starting from an empty notebook.

1. Understand the notebook

A notebook contains cells. The cell type matters.

Cell type Use it for Run it with
Markdown headings, explanations, links, lists, and LaTeX equations Shift+Enter
Code Python instructions that produce output or change variables Shift+Enter

Run the supplied notebook from top to bottom once before editing. A later cell can depend on variables or imports created earlier.

Use Kernel → Restart Kernel and Run All Cells before submission. This catches hidden state, missing setup cells, and code that only worked because cells were run out of order.

When a command is unfamiliar

Use the notebook’s command detective routine:

  1. run the small working example;
  2. read the output or the last line of the error;
  3. use help(command), command?, or the official documentation;
  4. change one input in the supplied sandbox; and
  5. use the command in the task and keep fixing it until the check passes.

Suitable examples include np.array, .shape, .dtype, .mean(), np.diff, np.asarray, np.allclose, Boolean masks, and plt.plot.

2. Begin with named quantities

voltage_V = 9.0
resistance_ohm = 1000.0
current_A = voltage_V / resistance_ohm
current_mA = current_A * 1000

print(f"Current: {current_mA:.2f} mA")

The part before = is a variable name. The part after = is evaluated and stored. Python does not automatically know that 9.0 is a voltage, so include the unit in the name.

Comments begin with #:

resistance_ohm = 2200.0  # 2.2 kΩ written in base ohms

First checkpoint

Change the resistance to 2200.0. Run the code. Add an assertion that checks the current is positive.

3. Store several values

A Python list stores an ordered collection:

resistor_values_ohm = [1000.0, 2200.0, 3300.0, 4700.0]

print(resistor_values_ohm[0])   # first item
print(resistor_values_ohm[-1])  # last item
print(len(resistor_values_ohm))

Python starts indexing at zero. A loop repeats an operation:

for value_ohm in resistor_values_ohm:
    current_mA = 9.0 / value_ohm * 1000
    print(value_ohm, current_mA)

4. Meet NumPy

NumPy arrays store numerical data and support vectorized operations: one expression can calculate every item.

import numpy as np

voltage_V = np.array([1.5, 3.0, 4.5, 6.0, 7.5, 9.0])
resistance_ohm = 2200.0
current_mA = voltage_V / resistance_ohm * 1000

This produces six currents because the division is applied to all six voltages.

Inspect the data before interpreting it:

print(type(voltage_V))
print(voltage_V.shape)
print(voltage_V.dtype)
print(voltage_V)
print(current_mA)

Useful array operations include:

current_mA[0]                 # first result
current_mA[-1]                # last result
current_mA.min()
current_mA.max()
current_mA.mean()
current_mA[current_mA < 3.0]  # Boolean filter

NumPy will later store matrix rows, but this lesson uses only one-dimensional arrays. You should understand the data before using a linear-algebra solver.

5. Write a reusable function

def calculate_current_mA(voltage_V, resistance_ohm):
    """Return resistor current in milliamperes."""
    return np.asarray(voltage_V) / resistance_ohm * 1000

Call and verify the function:

test_current_mA = calculate_current_mA([3.0, 6.0, 9.0], 3000.0)

assert np.allclose(test_current_mA, [1.0, 2.0, 3.0])

An assertion is a check, not the main calculation. np.allclose is used for decimal calculations because computers may store a result such as 0.3 as a number that is extremely close to, but not exactly, 0.3.

6. Read the documentation

Start with the object you are using:

help(np.round)

In Jupyter, this also opens help:

np.round?

Read the function signature, then the parameter descriptions, return value, and examples. Do not guess parameter names.

Read an error from the bottom

When Python shows a traceback, start with the last line. Then look one line above it for the code that failed.

Last line says Meaning Check
missing required positional argument The function needs another value Compare your call with the function signature
unexpected keyword argument The keyword name is not accepted Copy the exact parameter name from the documentation
AssertionError A check was false Print both values; use np.allclose for decimal arrays

For a larger library, search the official documentation for the function name. Compare the signature with your line of code from left to right. Fix one mismatch and run the cell again.

The notebook contains this intentional error behind a switch:

trigger_documentation_error = True

if trigger_documentation_error:
    rounded_current_mA = np.round(current_mA, digits=2)

Read the final exception line. Open the official numpy.round documentation, find the correct keyword, repair only that keyword, and rerun the cell until it prints the rounded array.

Use the full documentation and help-request lesson when the first lookup does not solve the problem. That lesson also covers Google searches, Stack Overflow, minimal reproducible examples, and the evidence required when asking the teacher.

7. Graph an array

import matplotlib.pyplot as plt

plt.plot(voltage_V, current_mA, marker="o")
plt.xlabel("Voltage (V)")
plt.ylabel("Current (mA)")
plt.title("Current through a 2.2 kΩ resistor")
plt.grid(True)
plt.show()

A graph is not finished until the axes, units, title, and data are clear. Add a numerical slope check in code.

Coding assignment: resistor investigation

Create a notebook section titled My resistor investigation. Use a \(2.0\,\mathrm{k\Omega}\) resistor and the six supplied voltage values. These numbers give clean whole-number currents.

Your submission must include:

  1. named variables with units;
  2. the supplied NumPy voltage array;
  3. one current calculation using the supplied function;
  4. one printed current selected by its position;
  5. one np.allclose check; and
  6. a graph with a title, labelled axes, units, markers, and grid.

Starter

The downloaded notebook divides this starter into four short code cells. Change only the lines marked TODO.

student_resistance_ohm = 2000.0
student_voltage_V = np.array([2, 4, 6, 8, 10, 12])

student_current_mA = calculate_current_mA(
    student_voltage_V,
    student_resistance_ohm,
)
assert np.allclose(student_current_mA, [1, 2, 3, 4, 5, 6])

Do not copy a completed analysis from a search result. Use documentation to understand individual functions, then write and verify your own investigation.

Optional challenge

Compare two resistor values on the same graph. Use the same voltage array for both, add labels and a legend, and add a check using np.allclose.

Submit

Submit the downloaded .ipynb file. Before submitting:

Next lesson

After this assignment, complete From Two Loops to a Matrix. The new idea in that lesson should be translating circuit equations into matrix rows, not learning Jupyter and NumPy at the same time.

Help improve this lesson (optional)

If something got in the way, tell the teacher which step or word was unclear, what you still do not know how to do, and one change that would help the next student. If you can fix the wording, example, screenshot, or starter code, show the teacher. A useful fix may be added to the course website and credited to you.