Index Ai Academy
Phase 0 · Python core

Review: find the slip (Python core)

Ten slips that run without an error, found by working a tiny input by hand, and the construct sheet for NumPy and PyTorch code.

About 30 minutes · Free lesson

What it covers8

Why it matters

The slips that cost the most time raise no error: the code runs and the answer is quietly wrong. The twenty-four lessons before this one each end with practice on their own idea, but none asks you to find a slip among all the ideas at once. That's the job in real code, and in AI code the same ten slips cause the same symptoms: a noisy average loss, results leaking from one run to the next, a layer that never trains. Learn their faces here, on twenty lines, and they get cheaper to spot everywhere.

What you'll be able to do

  • Find a slip in a function by working a tiny input by hand and comparing it with what the code should do
  • Name ten common Python slips: an accumulator reset in the loop, print for return, a shared list, sort() returning None, a broad except, = for ==, an off-by-one range, text compared as numbers, a missing self., and a list changed while looped over
  • Match each Python construct in the core to the NumPy or PyTorch line where you will meet it
Quick check
A guess before you start: this function is meant to add up the spends. What does total_spend([5, 7]) return?
def total_spend(rows):
    for r in rows:
        total = 0
        total += r
    return total

print(total_spend([5, 7]))
  1. 7
  2. 12
  3. 0
  4. 5
Show the answer

7

total is set to 0 on every pass of the loop, so only the last value survives: 7. The code runs without an error and gives a wrong answer.

The idea: a slip runs, and the answer is wrong

This review rests on the whole Python core: Variables, Loops, Functions, Lists, Errors and exceptions, Classes and Inheritance.

The slips that cost the most time raise no error. Python does what you typed, not what you meant, and the answer comes out wrong and plausible. You can't see one by running the code once. You find it by reading the code the way a reviewer does: pick a tiny input, work it out by hand, and compare it with what the code says. This lesson has ten such slips, one at a time, so that when you meet them in a training script you know their faces.

Quick check
From the lesson on lists: what does this print?
scores = [3, 1, 2]
print(scores.sort(), scores)
  1. None [1, 2, 3]
  2. [1, 2, 3] [1, 2, 3]
  3. An error
  4. [1, 2, 3] None
Show the answer

None [1, 2, 3]

list.sort() sorts the list itself and returns None, so printing its result gives None while the list is now sorted.

Try it now

Step through. Five moves find nearly every slip in a small function.

In your own words
In your own words: why is a slip that raises no error harder to find than one that does?

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

In Python: ten slips, found one at a time

Purpose. Learn the faces of ten slips. Six are in the code below; mark every line that has one.

What each of the six looks like

The reset in the loop. A running total must be set once, before the loop. Put total = 0 inside, and every pass throws away what the pass before it added. The code runs, and the answer is just the last item.

print for return. print shows a value on the screen and gives back None. A function that prints its answer looks right when you call it by itself and breaks the moment its caller tries to use the value. Use return for anything another line of code needs.

sort() returns None. A list's sort method rearranges the list in place. Writing names = names.sort() leaves names as None. sorted(names) returns a new sorted list and leaves the original alone.

A shared default list. In def add_tag(tag, tags=[]) the empty list is created once, when the function is defined, and every call that doesn't pass its own list shares it. The fix is tags=None and a fresh list made inside the function.

= for ==. One equals sign assigns, and two compare. Python refuses an assignment in an if, so this one at least shows itself. The quiet version runs the other way: count == 0 on a line of its own compares, throws the answer away and changes nothing.

An off-by-one range. range(a, b) starts at a and stops before b. Start at 1 and you skip the first item, because positions start at 0.

Quick check
What does this print?
def double(x):
    print(x * 2)

y = double(4)
print(y)
  1. None 8
  2. An error
  3. 8 8
  4. 8 None
Show the answer

8 None

double prints 8 on the way, but returns nothing, so y gets None and the last print shows None. The caller can't use the value because the function only displayed it.

Four slips that need a drill

The next four run too, and each hides in code that looks fine. Text for numbers: a value read from a file or a form is text until you convert it, and text compares one character at a time, so "9" is above "100". A missing self.: without it, a line in a method makes a local variable that vanishes when the method ends, and the object never changes. A list changed while you loop over it: removing an item shifts the rest left and the loop steps past the next one. A broad except: catching every exception turns a typo into "bad data" and hides it. Each drill below starts with the slip in place: find it, fix it, and run the checks.

Drill

The highest score is 9

These scores arrived as text. The code should set best to the highest score as a number, 100, but it picks "9". Find the slip and fix it.

scores = ["10", "9", "100", "25"]
best = max(scores)
print(best)
In the lesson, your code is checked as you write it.
Drill

The counter that stays at zero

Two calls to add() should leave c.count at 2, but it stays 0. Find the one slip and fix it.

class Counter:
    def __init__(self):
        self.count = 0

    def add(self):
        count = self.count + 1

c = Counter()
c.add()
c.add()
print(c.count)
In the lesson, your code is checked as you write it.
Drill

Removing while looping

This should leave only the odd numbers, [1, 3], but an even number is left behind. Find the slip and fix it.

nums = [1, 2, 2, 3, 4]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)
In the lesson, your code is checked as you write it.
Drill

The except that hides a typo

The loop should add the numbers and list the bad text: total 11 and skipped ['x']. Instead everything is skipped. Find the slip, then fix both the handler and what it was hiding.

values = ["4", "x", "7"]
total = 0
skipped = []
for v in values:
    try:
        total += int(v)
        print("added", vv)
    except Exception:
        skipped.append(v)
print(total, skipped)
In the lesson, your code is checked as you write it.
Quick check
What does this print?
print(list(range(1, len([10, 20, 30]))))
  1. [1, 2, 3]
  2. [0, 1, 2]
  3. [0, 1]
  4. [1, 2]
Show the answer

[1, 2]

range(1, 3) starts at 1 and stops before 3, so it gives 1 and 2. Starting at 1 also skips the first position.

Quick check
What does this print?
nums = [1, 2, 2, 3]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)
  1. [3]
  2. [1, 2, 3]
  3. [1, 3]
  4. [1, 2]
Show the answer

[1, 2, 3]

After the first 2 is removed the list shifts left, and the loop steps past the second 2. One even number is left behind: [1, 2, 3].

Quick check
Which slip is this? A function returns names.sort() and its caller finds None.
  1. list.sort() works in place and returns None
  2. A missing import at the top of the file
  3. The list was empty when it was sorted
  4. An off-by-one in a range further down
Show the answer

list.sort() works in place and returns None

sort changes the list and returns None. The fix is sorted(names), or sort first and return the list.

In your own words
Pick two of the ten slips and say how you'd catch each without running a long program.

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

In AI work: the same slips, in a training script

Purpose. Each of the ten slips has a version in AI code, and each has a symptom you can learn to recognize.

A one-page Python sheet

Each construct from the Python core, with the line where you'll meet it in a NumPy or PyTorch script:

ConstructWhat it doesWhere you'll meet it
for with a running totaladds up values one by oneloss_sum += loss.item() in every training loop
return, not printhands a value to the callerdef forward(self, x): return ...
a list passed to a functionthe function can change the caller's lista batch list changed inside a transform
sort() against sorted()in place against a new listsorted(scores), np.sort(scores)
self. in a methodstores a value on the objectself.layer = nn.Linear(4, 2) in __init__
== against =compares against assignsif preds == labels, a mask in NumPy
range(a, b)stops before bfor epoch in range(epochs)
int(), float()text to a numbera CSV column before torch.tensor
except ValueErrorcatches one named erroraround json.loads and int()
withenters, runs, always exitswith torch.no_grad():
__call__lets an object be calledmodel(x)
Worked example

Worked example: reading a function the reviewer's way

A teammate's helper should return the three best scores, highest first. Read it with a tiny input.

def best_three(scores):
    ranked = scores.sort()
    return ranked[::-1][:3]

def best_three_fixed(scores):
    ranked = sorted(scores)
    return ranked[::-1][:3]

data = [5, 9, 1, 7]
print(best_three_fixed(data))
try:
    best_three(data)
except TypeError as e:
    print("slip:", e)
It runs right here in your browser, with nothing to install.

With the tiny input [5, 9, 1, 7] the right answer is [9, 7, 5]. Working the first version by hand: scores.sort() returns None, so ranked is None, and slicing None fails with a TypeError. The fix is sorted(), which returns a new list. Note that sort() also changed the caller's list, a second reason to prefer sorted().

In your own words
Which of the ten slips would you check first in a script whose average loss looks too noisy, and why?

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

Practice what you just read

  • 1 code example you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

A function has print(total) as its last line, and its caller gets None. What is the slip?

  1. print instead of return
  2. A missing import at the top of the file
  3. An off-by-one range
  4. sort() returning None

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 127 lessons

Free Python developer course

Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.

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