Code is the last step, not the first. Before any language, there is thinking: breaking a task into steps, naming the things you need to remember, deciding what to do when things differ, and repeating work without writing it twice. This lesson is that thinking, with no code at all.
Difficulty: Beginner · Know this first: F03 — Programming: Writing the Instructions
The bar below is a worked example for this lesson, not a measurement. It shows shares of 100 for the thinking time on a task. The shape is the point: breaking the task down is most of the thinking. Switch the scenario and watch the decision share grow when the task gets messy.
Extra diagram · from scratch to master
Start with one vague task. Cut it into steps until each step is small enough to do in one go.
Extra diagram · from scratch to master
Follow a pile of numbers through a decision and a repeat, and watch the biggest one emerge.
Break a task into steps yourself. Type a task as small steps separated by commas, and watch the tool count the steps, the decisions, and the repeats. Or pick a ready-made task. The counting is exact. The lesson is the shape: a task is steps, decisions, and repeats, nothing else.
A line that starts with "if" counts as a decision. A line with "each" or "repeat" counts as a repeat. Try: "if the water is boiling, pour it, repeat for each cup".
Try this: (1) Make tea gives 4 steps, 0 decisions, 0 repeats. (2) Type "if the water is boiling, pour it, repeat for each cup". That is 3 steps, 1 decision, 1 repeat. (3) Find the biggest number gives 5 steps, 1 decision, 1 repeat.
Three questions. No score is saved anywhere — this is just you against the material.
I take the same thinking four times here. First I break a task into steps. Then I name boxes and write decisions. Then I build reusable pieces. Last I take apart a real system.
Definition: Thinking in steps means breaking a task into small actions, in order. Each step is one thing. If a step feels big, I break it again. I say the task in one sentence and I say what done looks like before I start.
Types:
Uses: I use this for every task, not just programs. Cooking, packing, fixing a machine. The thinking is the same.
Dimensions: One task, a few steps, one person. What breaks first is a vague task, and I notice it when the steps do not make sense. It costs minutes to write the steps down. It costs hours when I skip this and start doing before I start thinking. The trade is simple: thinking first is slow at the start and fast at the end.
Definition: At this level I name the things I need to remember, I write the decisions as questions with two answers, and I repeat steps for each item in a pile. A variable is a named box. A decision is if this, then that. A repeat is do this for each one, with an end.
Types:
Uses: I use this to turn a plan into something a machine can run. Steps alone are a recipe. Boxes, decisions, and repeats are a program.
Dimensions: A task with choices and a pile to work through. What breaks is a decision with a vague question, and I notice it when two people read the same step and do different things. It costs care to write exact questions. The trade is that exact questions cost words, and they buy steps anyone can follow.
Definition: At this level I take a set of steps I use more than once and give it a name. That is a function. Make tea is a function. Sort one file is a function. The big task becomes small functions used together, and each function can be checked on its own.
Types:
Uses: I use this when a plan gets long. I split it into named pieces, check each piece alone, and then put the pieces together.
Dimensions: A task of many pieces, used by more than one person. What breaks is a piece with a vague name, and I notice it when nobody knows what it does without reading all its steps. It costs thought to name pieces well. The trade is that good names cost a minute, and they save every reader after you an hour.
Empty input breaks the steps. A list of steps that works on five items can break on zero items. I test the empty case on purpose, because real systems send empty lists all the time. A program that handles zero items calmly is a program that survives a quiet day.
$ python3 -c "
def first(items):
if not items:
return 'nothing here'
return items[0]
print(first([]))
print(first(['a', 'b']))"
nothing here
a
Every flag in the commands above, letter by letter.
python3 -c: -c means run the string that follows as code. The quotes hold the program. Without -c, python3 expects a filename.python3 -m runs a module by name. python3 -m json.tool reads JSON and prints it indented. It is the flag I reach for when a tool ships as a module instead of a file.Check it: run python3 -c "print(1+1)". It prints 2. Then run echo '{"a": 1}' | python3 -m json.tool.
Try it: run the code above, then remove the if not items check and run it again. It crashes with an IndexError on the empty list. The check is two lines. The crash it prevents happens at 3 in the morning.
The loop that never ends. A while loop with a condition that never turns false runs forever. I always give a loop a way out, and I test the exit with a timeout. If the timeout fires, the exit is broken.
$ timeout 2 python3 -c "
n = 0
while n < 3:
n += 1
print('done, n =', n)"
done, n = 3
$ timeout 2 python3 -c "while True: pass"; echo $?
124
Every flag in the commands above, letter by letter.
timeout 2: the 2 is seconds. After 2 seconds, timeout sends TERM to the command. echo $? prints the exit code. 124 means timeout had to kill it.timeout -v prints a line when it sends the signal, like timeout: sending signal TERM to command 'sleep'. Without -v, the kill happens silently, and I have to guess whether the timeout fired or the program finished.Check it: run timeout -v 1 sleep 5; echo $?. It prints the sending signal line, then 124. Run it without -v and the line is gone.
Try it: run both commands. The first finishes and prints done, n = 3. The second is killed by timeout and prints 124. The difference is one exit condition. I test every loop with a timeout until I trust its exit.
Definition: At this level I take a system I did not build and break it into its pieces, the same way I break a task into steps. I find the inputs, the outputs, the decisions, and the repeats. I draw the steps before I change anything, because changing a system I do not understand is how incidents happen.
Types:
Uses: I use this when I join a team or inherit a system. I take it apart on paper first. I do not change code until I can draw the steps.
Dimensions: A system with many pieces, many people, many users. What breaks is the piece nobody decomposed, and I notice it when a small change breaks something far away. It costs real time to take a system apart carefully. The trade is that the time costs days, and a change made blind costs incidents.
Test each branch, not just the happy path. A decision with three branches needs three tests. I run all three and write down what each one returns. If a branch is never tested, it is never known to work. The login check below has three branches, and I test all three.
$ python3 -c "
def login(password):
if len(password) < 8:
return 'reject: too short'
if password.isdigit():
return 'reject: numbers only'
return 'accept'
for pw in ['abc', '12345678', 'correct-horse']:
print(pw, '->', login(pw))"
abc -> reject: too short
12345678 -> reject: numbers only
correct-horse -> accept
Try it: run the code above, then add a fourth password of your own and predict the result before you run it. If your prediction is wrong, the rule in your head is wrong, and that is worth finding out now.
Order of steps is a decision. The same steps in a different order give a different answer. I check a password is long enough before I check what it contains, because the short check is cheaper and it fails faster. Cheap checks first, expensive checks last. That order saves real time when the input is bad.
$ python3 -c "
def login(password):
if len(password) < 8:
return 'reject: too short'
if password.isdigit():
return 'reject: numbers only'
return 'accept'
print(login('abc'))
print(login('correct-horse'))"
reject: too short
accept
Try it: swap the two checks in the code and run it again with '12345678'. The answer is the same, but the order of work changed. For two checks it does not matter. For a check that reads a file or calls a server, the order matters a lot.
Order is part of the thinking. Step 2 cannot run before step 1 if it needs what step 1 makes. Pour the water before you boil it and you get a cold cup. Most bugs in real programs are steps in the wrong order, not steps that are wrong on their own.
Names are the map. A box called x tells the next reader nothing. A box called biggest tells them everything. I spend real time on names, because the next reader is often me, six months later, and I will have forgotten what x meant.
A decision needs both sides written down. If yes, do this. If no, do that. A decision with only one side is a decision the next reader has to guess, and guesses are where bugs live.
At 10x the size, the plan does not change shape. It gets more pieces, and each piece gets its own small plan. The thinking is the same. The paper is bigger.
At 100x, the plan is the design of the whole system. Breaking a system into pieces, naming the pieces, and writing down how they talk is the whole job of a senior engineer. It is this lesson, at scale.
biggest = first number
for each next number:
if number is bigger than biggest:
biggest = number
show biggest
That is the whole find-the-biggest plan, written as steps. Read it top to bottom. The box starts with the first number. Each new number asks the question. The box changes only when the answer is yes.
Try it: three passwords, three branches. Run the login check with 'abc', '12345678', and 'correct-horse'. Each one takes a different branch, and each branch prints a different answer. That is the test list for this function. Three branches, three tests. If you add a fourth rule, you add a fourth test.
$ python3 -c "
def login(password):
if len(password) < 8:
return 'reject: too short'
if password.isdigit():
return 'reject: numbers only'
return 'accept'
for pw in ['abc', '12345678', 'correct-horse']:
print(pw, '->', login(pw))"
abc -> reject: too short
12345678 -> reject: numbers only
correct-horse -> accept
A plan for sending a message to every person on a list had no end to its repeat. It said: take the next person, send the message, take the next person, send the message. It never said what to do when the list ran out. The person following it kept going, sent the same message twice to the first people, and only stopped when someone noticed.
Two things. First, every repeat gets an end written down before anything runs. Second, I check a plan by walking through it with a tiny example: two people on the list, not two hundred. A tiny example shows the missing end in a minute. A big list shows it after the damage is done.
Break down the task of finding the cheapest price in a list of prices. Write the steps, name the boxes, write the decisions, and say when the repeat ends. No code. Just the plan.
Start with the plan. About six lines: take the first price as the cheapest, take the next price, ask if it is cheaper, keep it if yes, repeat for each price, show the cheapest. For 100 prices that is 100 looks and 100 questions. For 10 million prices it is still one look each. The thinking is the same size whatever the list is.
A short plan is easy to read and easy to get wrong at the edges. A longer plan that checks the empty list costs one step and saves a crash. The trade is that every check costs a line, and it buys a plan that works on the real list, not just the happy one.