Index Ai Academy
Phase 0 · Numbers for code

Ranges and edges in code

At least, under and between as symbols; intervals with each end in or out; bands with no gaps.

About 32 minutes · Free lesson

What it covers7

Why it matters

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.

What you'll be able to do

  • Test for an interval with a chained comparison, and check it at its two edges
  • Cut the number line into half-open bands with no gap and no overlap, in an if/elif chain, a slice and range()
  • Predict // and % below zero, and use % to wrap an index or a clock around
  • Clamp a value into a range with min and max, and see the same idea in np.clip and torch.clamp
Quick check
A guess before you start. Someone is exactly 18. What does this print?
age = 18
print(18 <= age < 25, 18 < age <= 25)
  1. True False
  2. False True
  3. False False
  4. True True
Show the answer

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.

The idea: a number, an edge, and which side it falls on

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.

Quick check
From the Foundation: what is the opposite of "at least 50"?
  1. Over 50: x > 50
  2. At most 50: x <= 50
  3. Under 50: x < 50
  4. Exactly 50: x == 50
Show the answer

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.

Try it now

Whenever you write an interval, test both of its edges before you trust it.

Quick check
Which test is True for exactly the whole numbers 3, 4, 5 and 6?
  1. 3 < n < 7
  2. 3 < n <= 7
  3. 3 <= n < 7
  4. 3 <= n < 6
Show the answer

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.

Quick check
A sign-up form offers the age groups "18–24", "25–34" and "35–44". Someone's age is stored as 24.5. What goes wrong?
  1. Nothing goes wrong: 24.5 is rounded down, so the first group takes them
  2. They fall in a gap: 24.5 is above 24 and below 25, so no group takes them
  3. They fall in an overlap: 24.5 belongs to the first two groups at once
  4. They join the last group, since a chain always ends at its last band
Show the answer

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.

In your own words
Why do half-open bands, such as [0, 50) and [50, 100), fit together with no gap and no overlap?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: the same edges, in five tools

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)
It runs right here in your browser, with nothing to install.

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)
Quick check
From the Decisions lesson: a chain stops at the first test that's True. What does this print?
spend = 100
if spend < 50:
    band = "small"
elif spend < 100:
    band = "medium"
else:
    band = "large"
print(band)
  1. small
  2. medium
  3. medium large
  4. large
Show the answer

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.

Worked example

Worked example: grade bands with no gaps

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)
In the lesson you can change this and run it.

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.

Drill

Is the room comfortable?

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)
In the lesson, your code is checked as you write it.
Drill

One gap, one overlap

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)
In the lesson, your code is checked as you write it.
Drill

When did the flight leave?

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)
In the lesson, your code is checked as you write it.

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.

In your own words
In your own words: what does max(0, min(x, 100)) do to x?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI work: clamp, batch and signed errors

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.

Quick check
What does this print?
rows = list(range(10))
sizes = []
for i in range(0, 10, 4):
    sizes.append(len(rows[i:i + 4]))
print(sizes)
  1. [3, 3, 3, 1]
  2. [4, 4, 4]
  3. [4, 4, 2]
  4. [4, 4]
Show the answer

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

In your own words
Where in a training loop would an off-by-one at an edge hide, and how would you find it?

Write a sentence or two, then compare it with a good answer in the lesson.

Goes deeper in

Practice what you just read

  • 7 code examples you can edit and run
  • a practice exercise that checks your code
  • a 6-question quiz
  • 10 review cards for spaced repetition

Try a quiz question

A ride's sign says "You must be over 120 cm tall." Which test matches the sign?

  1. height > 120
  2. height >= 120
  3. height < 120
  4. height <= 120

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 0 · about 32 hours of study

Tools

Python, the terminal and calling APIs 46 lessons All free
  1. Your first program FreeRun Python, print output, and read an error message without panicking.24 min
  2. Typing code exactly FreeBrackets, quotes, indentation and the look-alike characters that stop a program.26 min
  3. Variables FreeGive values names so your program can remember and reuse them.24 min
  4. Numbers and arithmetic FreeIntegers, decimals, rounding, and the math behind every metric.30 min
  5. Strings and f-strings FreeWork with text: join it, slice it, clean it, and format it.30 min
  6. Decisions with if/else FreeCompare values and choose what happens next.35 min
  7. Fractions, ratios and rates FreeShares, rates, percentage points and ratios, with Python doing the arithmetic.35 min
  8. Ranges and edges in code FreeAt least, under and between as symbols; intervals with each end in or out; bands with no gaps.32 min
  9. Lists FreeKeep many values in order, then index, slice and change them.28 min
  10. Files, folders and paths FreeWhat a file's name tells you, paths as directions through folders, and where a relative path starts.30 min
  11. Loops FreeRepeat work over every item without copy-pasting code.35 min
  12. Formulas: order, powers and rearranging FreeWork a calculation in the right order, fill in a formula, and turn it around to find what's missing.24 min
  13. Loops that add and count: sequences, sums and combinations FreeSequences that add or multiply each step, a formula for any term, and adding a sequence up.34 min
  14. Dictionaries FreeLook values up by name: the shape of almost all real-world data.40 min
  15. Functions FreePackage steps into reusable, testable pieces with inputs and outputs.35 min
  16. While loops FreeRepeat until something changes: goals reached, answers valid, tasks done.38 min
  17. Functions as values FreeStore functions, pass them in with key=, and accept any number of arguments.40 min
  18. Comprehensions FreeFilter and transform a whole collection in one readable line.38 min
  19. Errors and exceptions FreeRead tracebacks, and handle the failures you expect.38 min
  20. Finding bugs when nothing crashes FreeA method for wrong answers: expected against actual, reproduce, look inside, fix one thing.36 min
  21. Sets: unique items and fast lookups FreeDuplicates, fast membership, set operations and comparing two lists.34 min
  22. Modules and imports FreeUse Python's standard library instead of reinventing it.38 min
  23. Classes and objects FreeBundle data with the functions that work on it.38 min
  24. Inheritance and class attributes FreeBuild classes on other classes, and share values across every object.35 min
  25. Review: find the slip (Python core) FreeTen slips that run without an error, found by working a tiny input by hand, and the construct sheet for NumPy and PyTorch code.30 min
  26. JSON FreeThe text format APIs and LLMs use to exchange structured data.34 min
  27. Files and CSV data FreeRead and write files, and turn a spreadsheet export into Python data.33 min
  28. NumPy arrays FreeDo math on whole columns at once, the foundation of every ML library.30 min
  29. NumPy in practice: shapes, types and picking values FreeReshape, view and copy, where and clip, top-k, stacking and the (N, C, H, W) batch a model expects.35 min
  30. DataFrames with pandas FreeLoad a table, pick rows and columns, and summarize groups in a few lines.40 min
  31. Charts with Matplotlib FreeLine, bar, scatter, histogram and box plots, labeled and honest.42 min
  32. Project: images are arrays FreeGray, crop, brighten, watermark and palette tools built on NumPy and Pillow.45 min
  33. The terminal FreeNavigate folders and run programs by typing commands.30 min
  34. Version control with git FreeSave snapshots of your work, undo mistakes, and share code.30 min
  35. Packages and environments FreeInstall libraries with pip and keep projects isolated with venv.25 min
  36. Python on your own computer FreeInstall Python and VS Code, make a virtual environment, then run, debug and test a project.45 min
  37. How APIs work FreeRequests, responses, methods, status codes and headers.30 min
  38. Calling APIs from Python FreeSend requests, read JSON responses, and handle failures.35 min
  39. API keys and secrets FreeAuthenticate safely and keep keys out of your code.25 min
  40. Your first LLM call FreeSend messages to a model and read its reply, tokens and stop reason.30 min
  41. Capstone: ad-copy reviewer FreeCombine files, functions, JSON and an LLM call into one small tool.40 min
  42. Dates, times and time zones Freedatetime, timedelta, formats, time zones and the traps when clocks change.42 min
  43. Regular expressions FreeFind, check, extract and clean text patterns with the re module.42 min
  44. Sending email and text messages FreeEmailMessage, smtplib, mail merge and an SMS API, with secrets kept out of code.42 min
  45. Web pages: HTML and CSS FreeRead and write HTML, what forms send, CSS selectors and escaping.42 min
  46. Scraping web pages FreeBeautiful Soup, one record per item, pagination and robots.txt.45 min
Part of a free course 32 lessons

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.

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