Start Here: Python and the Math the Labs Use
Welcome. This is the first step of the Guided Foundations Path, and it assumes nothing — no programming, no calculus, no university-level mathematics. By the end you will be able to run the code in every other lesson in this catalog, and to read the four mathematical ideas those labs use over and over: a sum, an average, an area under a curve, and a slope.
You will not install anything. Every shaded code block on this page runs in your browser.
What the Run cell does#
Throughout this site, a block like the one below is a live Python cell:
readings = [2.0, 4.0, 6.0, 8.0]
total = sum(readings)
print("total:", total)
Two buttons sit above it:
- Run sends the code to a Python interpreter that has been downloaded into your browser. The output appears underneath. Nothing is installed on your computer.
- Edit lets you change the code before running it again.
Two things to know before you press anything:
print(...)is how code speaks to you. Anything insideprintshows up as output. A calculation that is not printed produces no visible output — the computer did the work but did not tell you.- Every cell is its own little program. Cells on a page do not share memory. If the second cell needs a value, it must define or import it again. (This is why each lab below re-imports
numpy.)
Go ahead and press Run on the cell above. You should see:
total: 20.0
How to read an error message#
Python is not angry at you when it fails — it is telling you exactly where it got stuck. Suppose you mistype readings as readigs:
Traceback (most recent call last):
File "<exec>", line 2, in <module>
NameError: name 'readigs' is not defined. Did you mean: 'readings'?
Read a traceback from the bottom up:
- The last line names the kind of problem and describes it.
NameErrormeans "I was asked to use a name I have never seen." The message even guesses the typo. - The lines above point at where it happened:
line 2of your cell. - The very first line,
Traceback (most recent call last), just tells you the order. Ignore it for now.
Your first error is normal and expected. It usually means a typo, a missing import (numpy not imported), or wrong indentation (spaces that do not line up). Fix it and run again.
Variables: giving a value a name#
A variable is a name attached to a value. You create one with =.
celsius = 20.0
fahrenheit = celsius * 9 / 5 + 32
print("celsius:", celsius)
print("fahrenheit:", fahrenheit)
Reading order: Python evaluates the right-hand side, then attaches the name on the left to the result. celsius * 9 / 5 + 32 is ordinary arithmetic; multiplication and division happen before addition.
Numbers come in two common flavours:
- An integer is a whole number:
3,-7,100. - A float is a number with a decimal point:
3.0,20.5,-0.001.
You can rename and reassign freely — the name always points at the most recent value:
steps = 10
steps = steps + 5
print(steps)
Lists: many values under one name#
A list holds several values in order, written with square brackets and commas.
sensor_readings = [12.5, 12.1, 12.9, 12.3]
print("all readings:", sensor_readings)
print("how many:", len(sensor_readings))
print("first:", sensor_readings[0])
print("last:", sensor_readings[-1])
The key idea is indexing: positions are counted from 0, so sensor_readings[0] is the first value and sensor_readings[1] is the second. Negative indices count from the end, so [-1] is the last value. len(...) tells you how many values there are.
That "start at 0" habit is not a quirk to memorise — it appears everywhere, so it is worth accepting early.
Making decisions: if and else#
An if runs a block of code only when a condition is true. The indentation (the spaces at the start of a line) is what marks the block — Python uses it instead of brackets.
battery_percent = 18
if battery_percent < 20:
print("Low battery: returning to the charging station.")
else:
print("Battery fine: continuing the task.")
Change 18 to 85 and run again: the else branch runs.
Comparisons produce a true-or-false value: == (equal to), != (not equal), <, <=, >, >=. Notice that testing equality uses a double equals sign — a single = assigns, a double == asks a question.
Repeating work: for loops#
A for loop runs the same block once for every value in a list. This is the single most useful habit in all of programming.
readings = [2.0, 4.0, 6.0, 8.0]
total = 0.0
for r in readings:
total = total + r
print("sum found by the loop:", total)
Read it as: for each value r in readings, add r to total. Before the loop total is 0.0; after the loop it holds the sum. The variable name r is arbitrary — Python creates it fresh on each pass.
This manual loop is exactly what the built-in sum(...) does for you. Seeing it once by hand makes sum feel obvious rather than magic.
Functions: naming a block of work#
A function is a named block of code you can reuse. Define it with def, then call it by name.
def average(values):
return sum(values) / len(values)
print("average of four readings:", average([2.0, 4.0, 6.0, 8.0]))
print("average of two readings:", average([10.0, 20.0]))
- The line starting with
defnames the function and lists its inputs (here,values). returnhands the result back to whoever called the function.- The body is indented; the blank line after it ends the function.
- The same function works on any list of numbers — that is the point of packaging work into a function.
numpy arrays: math on the whole list at once#
The labs in this catalog almost never use plain lists for numbers. They use numpy arrays, which look like lists but support arithmetic on every element at once. numpy is pre-loaded in the browser, so you only need to import it.
import numpy as np
readings = np.array([2.0, 4.0, 6.0, 8.0])
print("the array:", readings)
print("add 10 to every element:", readings + 10)
print("multiply every element by 2:", readings * 2)
print("element-by-element square:", readings ** 2)
print("mean (average):", readings.mean())
print("sum:", readings.sum())
print("first element:", readings[0], "last element:", readings[-1])
The crucial difference from a plain list: readings * 2 doubles every value, so the result is a new array with four numbers. With a plain list, * 2 would instead repeat the list — a classic trap. This "operate on the whole array at once" behaviour is called elementwise operation, and it is why numpy is everywhere in AI: a batch of 1,000 sensor readings is one array, and one line of code updates all of them.
Indexing and slicing work as with lists:
readings[0]— the first elementreadings[-1]— the last elementreadings[1:3]— elements at positions 1 and 2, i.e. a slice that stops before the second index
The math the labs use#
Four ideas appear in nearly every later lab. Each one is a plain-language idea dressed in symbols; the symbols are there to save words, not to add difficulty.
Sums#
A sum is just "add them all up." Mathematics writes it with a capital sigma:
Read the symbol as a compact for loop: start at , add each , stop at . In Python this is sum(values) for a list and arr.sum() for a numpy array. Example: .
Averages#
An average (or mean) answers the question: if every value were the same, what value would give the same total? It is the sum divided by how many values there are:
Example: sums to over values, so its average is . The average is a summary of a whole list in one number — useful, but note it hides how spread out the values are, which is a topic for the Probability lessons later on the path.
Area under a curve#
Some questions are about a total that changes as you go. If a car's speed is changing, the distance travelled is the area under the speed curve. You do not need calculus to see why. Split the journey into many short time slices. Within one short slice the speed is nearly constant, so the distance in that slice is approximately
Add up all those thin rectangles and you get the total distance — which is the area under the curve. Write for the height of the curve, for the width of each slice, and for the number of slices:
The more slices you use, the thinner each rectangle and the closer the total gets to the true area. In code, if x holds the slice edges and y holds the heights, the width is x[1] - x[0] and the sum of the left-edge rectangles is np.sum(y[:-1]) * width. There is no magic symbol in the code — it is the same "add up the rectangles" idea.
This is the idea behind definite integrals that later lessons assume, and it is why density curves in probability can be read as areas.
Slope as a rate#
A slope measures how fast one quantity changes when another changes. It is the rise divided by the run:
A slope of means: each extra unit of adds to . On a straight line the slope is the same everywhere. On a curve the slope changes from place to place, so we measure it between two nearby points. Pick two points very close together and the number settles down to the curve's slope at that spot. That limiting slope is what later labs call the derivative — and when there is more than one input, a partial derivative. You will meet those later as slopes, not as new mysteries.
Browser lab: sums, averages, area, and slope#
This lab does all four ideas on one small dataset. Press Run, then read the output line by line.
import numpy as np
import matplotlib.pyplot as plt
# --- Part 1: sum and average of a list of readings ---
readings = np.array([2.0, 4.0, 6.0, 8.0])
print("readings:", readings)
print("sum:", readings.sum())
print("average:", readings.mean())
# --- Part 2: area under the curve y = x^2 between x = 0 and x = 2 ---
# We tile the area with n thin rectangles and add their areas.
n = 100
x = np.linspace(0.0, 2.0, n + 1) # n + 1 edges, from 0.0 to 2.0
y = x ** 2 # height of the curve at each edge
width = x[1] - x[0] # every slice has the same width
height = y[:-1] # left edge of each rectangle
area = np.sum(height) * width
print("rectangles:", n)
print("estimated area under x^2 on [0, 2]:", round(float(area), 4))
print("exact area (x^3 / 3 from 0 to 2):", round(8 / 3, 4))
# --- Part 3: slope of y = x^2 near x = 1 ---
x1, x2 = 1.0, 1.1 # two nearby points
rise = x2 ** 2 - x1 ** 2
run = x2 - x1
print("slope of x^2 near x = 1:", round(rise / run, 4))
# --- Picture: the rectangles tile the area under the curve ---
fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(x[:-1], height, width=width, align="edge",
color="tab:blue", alpha=0.3, label="rectangles")
ax.plot(x, y, color="tab:red", linewidth=2, label="y = x^2")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Area under y = x^2 on [0, 2]")
ax.legend()
plt.show()
print("Notice: the four readings sum to 20 with average 5; 100 rectangles give area 2.6268 against the exact 8/3 = 2.6667 (more slices would close the gap); and the slope of x^2 near x = 1 is about 2.1.")
What to look for:
- Sum and average are the same two numbers you would get by hand.
- Area is close to, but a little below, the exact value — left-edge rectangles sit under a rising curve. Increase
nto1000and watch the estimate improve. - Slope of about
2.1: betweenx = 1andx = 1.1, each extra unit ofxadds about2.1toy. Shrink the gap by settingx2 = 1.01; the slope moves toward2.0.
Knowledge Check#
Test the loop and array behaviour and the slope and area ideas from above.
The slope of a line is its rise divided by its ______.
What does `np.array([1, 2, 3]) * 2` produce?
A lab estimates the area under a curve by adding up thin rectangles. If you use more, thinner rectangles, the estimate usually ______.
How many times does the body of `for r in [4, 8, 15, 16]: print(r)` run?
Your turn: predict, then check#
Now you drive. Below is a starter cell with two blanks. Before you run anything, read it and write down what you expect the output to be.
import numpy as np
# 1. Change these four readings to any numbers you like.
readings = np.array([12.0, 15.0, 9.0, 14.0])
# 2. Fill in the average. Hint: numpy has a mean function.
average = None
# 3. Fill in the slope between the points
# (x = 1, y = readings[0]) and (x = 3, y = readings[2]).
# slope = rise / run = (y2 - y1) / (x2 - x1)
slope = None
print("average:", average)
print("slope:", slope)
Your task:
- Replace the four readings with your own numbers.
- Replace the first
Nonewith the average ofreadings. - Replace the second
Nonewith the slope betweenreadings[0]andreadings[2](the run is3 - 1 = 2). - Before running, write down your predicted average and slope.
- Run the cell and compare. If they differ, check the arithmetic by hand and fix the code.
- In one sentence, explain the output — for the four readings above, that is: "The average is 12.5 because the readings sum to 50 over 4 values, and the slope is −1.5 because the reading falls 3 units over a run of 2."
If you can do this without any outside help, you have the Python and the math that every lab on the path assumes.
Key Takeaways#
- A live cell runs in your browser with Run;
print(...)is how code shows you its work, and a traceback is read bottom-up, with the useful message on the last line. - Variables name values, lists hold many values in order (counted from
0),if/elsechooses between blocks,forloops repeat work, and functions package reusable work under a name. - numpy arrays do arithmetic on every element at once —
readings * 2doubles the whole array. - A sum adds values, an average divides the sum by the count, an area under a curve is a sum of thin rectangles, and a slope is a rise over a run — a rate of change.
- You are not expected to already know any of this. You are expected to be able to run it, read it, change it, and explain it — which you just did.
Next Lesson#
Next: Probability Spaces and Events is step 2 of the Guided Foundations Path. Every lab from here on is a Python cell like the ones above, using the same four ideas on real data.