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.
Ten slips that run without an error, found by working a tiny input by hand, and the construct sheet for NumPy and PyTorch code.
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.
def total_spend(rows): for r in rows: total = 0 total += r return total print(total_spend([5, 7]))
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.
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.
scores = [3, 1, 2] print(scores.sort(), scores)
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.
Step through. Five moves find nearly every slip in a small function.
Write a sentence or two, then compare it with a good answer in the lesson.
Purpose. Learn the faces of ten slips. Six are in the code below; mark every line that has one.
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.
def double(x): print(x * 2) y = double(4) print(y)
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.
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.
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)
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)
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)
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)
print(list(range(1, len([10, 20, 30]))))
[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.
nums = [1, 2, 2, 3] for n in nums: if n % 2 == 0: nums.remove(n) print(nums)
[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].
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.
Write a sentence or two, then compare it with a good answer in the lesson.
Purpose. Each of the ten slips has a version in AI code, and each has a symptom you can learn to recognize.
Each construct from the Python core, with the line where you'll meet it in a NumPy or PyTorch script:
| Construct | What it does | Where you'll meet it |
|---|---|---|
for with a running total | adds up values one by one | loss_sum += loss.item() in every training loop |
return, not print | hands a value to the caller | def forward(self, x): return ... |
| a list passed to a function | the function can change the caller's list | a batch list changed inside a transform |
sort() against sorted() | in place against a new list | sorted(scores), np.sort(scores) |
self. in a method | stores a value on the object | self.layer = nn.Linear(4, 2) in __init__ |
== against = | compares against assigns | if preds == labels, a mask in NumPy |
range(a, b) | stops before b | for epoch in range(epochs) |
int(), float() | text to a number | a CSV column before torch.tensor |
except ValueError | catches one named error | around json.loads and int() |
with | enters, runs, always exits | with torch.no_grad(): |
__call__ | lets an object be called | model(x) |
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)
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().
Write a sentence or two, then compare it with a good answer in the lesson.
A function has print(total) as its last line, and its caller gets None. What is the slip?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
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