Free Python for AI course
Learn Python from your first line of code to your first call to a language model, with nothing to install.
At least, under and between as symbols; intervals with each end in or out; bands with no gaps.
A model says "spam" when its score is at least 0.5. A learning rate must stay above 0. A batch of 32 rows is cut from a data set of 100. An index must wrap from the last item back to the first. Each of these is a rule about where a number sits against an edge, and each goes wrong the same small way: one edge is off by one. This lesson takes the symbols and the number line from the Foundation and turns them into code that is right at the edges: chained comparisons, half-open bands, slices and range(), what // and % do below zero, and clamping.
age = 18 print(18 <= age < 25, 18 < age <= 25)
True False
The first test includes 18 at its lower end (<=), so 18 is in. The second leaves 18 out (<). One character decides which side of the line a number on the edge falls.
This lesson rests on Inequalities and true-or-false (Foundation lesson 18), which gave the four symbols and the interval, and on Numbers below zero (Foundation lesson 4), which put the number line through zero. Here is the one thing from them that code needs: > and < leave the edge out, >= and <= keep it, and the opposite of x >= 50 is x < 50, never x <= 50. If you skipped them, this is the whole of it.
Under 50: x < 50
"At least 50" includes 50, so its opposite leaves 50 out. Between them, x >= 50 and x < 50 cover every number exactly once.
An interval has three facts: where it starts, where it ends, and whether each end is included. On the number line a filled dot is an end that's in, and a hollow dot an end that's out. Press Next to move the edges of the age group 18 to 25.
Whenever you write an interval, test both of its edges before you trust it.
3 <= n < 7
It lets 3 in at the lower end and stops before 7, so 3, 4, 5 and 6 pass. Try each edge: 3 is in, 7 is out.
Bands. Cut the line into bands where each one includes its start and leaves out its end, and each ends where the next begins. Then every number lands in exactly one band. Written with whole-number ends ("0 to 49", "50 to 99"), a spend of 49.5 fits none: a gap. Written with both ends in ("0 to 50", "50 to 100"), a spend of 50 fits two: an overlap. Half-open bands have neither.
They fall in a gap: 24.5 is above 24 and below 25, so no group takes them
Whole-number ends leave a gap between 24 and 25. Half-open bands close it: 18 <= age < 25, then 25 <= age < 35, and 24.5 is in the first.
Below zero, the line still has one rule. Division with // rounds down, toward the left of the line, so the answer for a negative number goes further from zero than you might guess. Python's % gives the leftover that makes the pair add back up, and it is never negative when the divisor is positive. That is what lets a count wrap around a clock. The code part prints every number on this picture.
Write a sentence or two, then compare it with a good answer in the lesson.
Purpose. Write intervals, bands, slices, range and wrap-around so that they are right at the edges.
A chained comparison reads the way the math does, and means the same as two tests joined by and:
age = 25 print("18 <= age < 25: ", 18 <= age < 25) print("18 <= age <= 25:", 18 <= age <= 25) print("spelled out: ", 18 <= age and age <= 25)
An if/elif chain makes half-open bands without naming the lower end: each elif is only reached when the tests above it were False.
spend = 50 if spend < 50: band = "small" elif spend < 100: band = "medium" else: band = "large" print(spend, "is", band)
spend = 100 if spend < 50: band = "small" elif spend < 100: band = "medium" else: band = "large" print(band)
large
100 is not under 50, and not under 100 either, so the else runs. The medium band is [50, 100): it leaves 100 out.
Slices and range are half-open too. A slice keeps its start and leaves out its end, so slices sit side by side with nothing shared and nothing lost, and a slice's length is end minus start. range(start, stop, step) does the same, and cuts a data set into batches:
word = "abcdefgh" print(word[0:3], word[3:6], word[6:8]) print(len(word[2:5]), "characters, which is 5 - 2") rows = list(range(100)) for start in range(0, len(rows), 32): batch = rows[start:start + 32] print(start, len(batch))
The last batch starts at 96 and has 4 rows, because rows[96:128] stops at the end of the list instead of failing. Every row is in exactly one batch.
Below zero. Run the numbers from the picture, and the wrap-around that uses them. % with the length of a list turns any index, even -1 or one past the end, into a valid one. Negative indexes count from the end without it.
print(-7 / 2, -7 // 2, int(-7 / 2)) print(-7 % 2, (-7 // 2) * 2 + (-7 % 2)) items = ["a", "b", "c"] i = 2 print(items[(i + 1) % len(items)], items[(i - 3) % len(items)], items[-1])
-7 // 2 is -4 and int(-7 / 2) is -3, so they are different rules. The pair // and % always add back up to -7. Past the last item, index (2 + 1) % 3 is 0: the round-robin comes back to the start. Many other languages round toward zero, so this is a classic surprise when code moves between them.
A course gives an A from 90, a B from 80, a C from 70, and a D below that. Scores have decimals, so each band is half-open and the chained comparisons name both ends.
score = 79.5 if 90 <= score <= 100: grade = "A" elif 80 <= score < 90: grade = "B" elif 70 <= score < 80: grade = "C" else: grade = "D" print(score, "is a", grade)
79.5 is at least 70 and under 80, so it's a C. Written as "70 to 79" and "80 to 89", the same score would have matched nothing. Change the score to 80, then 89.99, then 90, and check that each lands in exactly one band. Only the top band keeps its upper end, because 100 is the highest score there is.
A thermostat calls a room comfortable when its temperature is from 18 degrees up to, but not including, 24. Below 18 it's too_cold; at 24 or above it's too_hot. Set the three variables to True or False from temp. For every temperature, exactly one of them should be True. The checks try the edges.
temp = float(input("Temperature? ")) comfortable = False # 18 up to, but not including, 24 too_cold = False # below 18 too_hot = False # 24 or above print(comfortable, too_cold, too_hot)
A courier charges by weight: under 2 kg costs $4, from 2 kg up to but not including 10 kg costs $9, and 10 kg or more costs $20. This program has two mistakes at its edges: one weight matches two rules, and some weights match none. Fix the tests so every weight gets exactly one price. The checks try the edges.
weight = float(input("Weight in kg? ")) price = 0 if 2 <= weight < 10: price = 9 if weight <= 2: price = 4 if weight > 10: price = 20 print(price)
A flight landed at hour 3 (3 a.m.) after 7 hours in the air. Set departure_hour to the hour it left, on a 24-hour clock from 0 to 23. Use % so it works for any landing time.
landing_hour = 3 flight_hours = 7 departure_hour = 0 print("Left at hour", departure_hour)
Clamping. Pulling a value back to the nearest edge of a range is clamping. min(x, high) brings anything above high down to it, and max(low, x) lifts anything below low up to it. The plot shows the result: a straight line that goes flat at both edges.
import matplotlib.pyplot as plt low, high = 0, 100 xs = list(range(-50, 151, 10)) ys = [] for x in xs: ys.append(max(low, min(x, high))) print(ys[:4], ys[-4:]) plt.plot(xs, ys) plt.xlabel("x") plt.ylabel("max(0, min(x, 100))")
The first values are all 0 and the last are all 100: -50 comes back as the lower edge, 150 as the upper, and values in between pass through unchanged. Change high to 60 and run it again.
max(0, min(x, 100)) do to x?Write a sentence or two, then compare it with a good answer in the lesson.
Purpose. The same edges show up in training code, with real names.
Libraries ship clamping so you don't write max(min()) by hand. NumPy calls it np.clip and PyTorch torch.clamp. Both clip a whole array at once, and each takes the low and high edge.
Batches are half-open bands. A training loop walks range(0, n, batch_size) and slices data[i:i + batch_size], the same pattern as the bands above. The last band is shorter, and no row is skipped or repeated.
Errors have a sign. In a model report an error is prediction - target: negative means too low, positive too high. abs() keeps the size and drops the direction, and negative logits are normal, not a bug.
preds = [38, 50, 45] targets = [45, 44, 45] errors = [] sizes = [] for k in range(3): errors.append(preds[k] - targets[k]) sizes.append(abs(errors[k])) print(errors, sizes) print(sum(errors), sum(sizes))
The signed errors add to -1 because a miss up cancels part of a miss down. The absolute errors add to 13, and 13 / 3 is the mean absolute error you will meet when models are scored.
rows = list(range(10)) sizes = [] for i in range(0, 10, 4): sizes.append(len(rows[i:i + 4])) print(sizes)
[4, 4, 2]
The starts are 0, 4 and 8. The last slice, rows[8:12], stops at the end of the list, so it has 2 rows.
Write a sentence or two, then compare it with a good answer in the lesson.
np.clip, np.where and masks over a whole array.A ride's sign says "You must be over 120 cm tall." Which test matches the sign?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Learn Python from your first line of code to your first call to a language model, with nothing to install.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write