Platform Engineering · Lesson F03

Programming: Writing the Instructions

Software is a list of instructions. Programming is writing that list. You pick a language, you write the steps in words the machine can turn into its own list, you run it, and you fix it when it breaks. This lesson does that whole loop once, slowly, with a real example.

Difficulty: Beginner · Know this first: F02 — Software: Instructions, Not Magic

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

The bar below is a worked example for this lesson, not a measurement. It shows shares of 100 for the effort of writing a first program. The shape is the point: writing is most of it the first time, and fixing takes over the moment something breaks. Switch the scenario and watch the shares move.

Extra diagram · from scratch to master

The loop: write, run, read, fix

Start with an idea. Add one step of the loop at a time until the program works.

6 steps in the loop1 loop that repeats1 answer at the end
The idea
one sentence
Write the code
one line at a time
Run it
see what happens
Read the error
the machine talks
Fix one thing
just one
Run again
check by hand
Request / flowResponse · the way backFailure / dead end

Extra diagram · from scratch to master

From words to machine steps

Follow your code as the machine turns it into its own instructions and runs them.

6 stages1 translator1 answer
Your code
words you wrote
The file
saved on disk
Translator
words to steps
Machine steps
the real list
CPU runs them
one at a time
Answer
on the screen
Request / flowResponse · the way backFailure / dead end

Try it: change the inputs and watch it bend

Run three tiny programs without installing anything. Pick a program, give it an input, and watch it run. The arithmetic is exact. The lesson is the loop: write, run, read, fix.

Pick a program

Each program is a few lines long. Double a number takes a number. Greet takes a name. Area takes the side of a square.

7

For Greet, the number is the length of the name. A name of 7 letters gives "Hello, friend of 7 letters!" Try 3 or 12 and watch it change.

Try this: (1) Double a number, input 7. The answer is 14. (2) Area of a square, side 7. The answer is 49, because 7 times 7 is 49. (3) Area, side 12. The answer is 144, because 12 times 12 is 144.

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

I take the same loop four times here. First I write a first program. Then I learn to read errors. Then I fix bugs I cannot see. Last I build programs other people use.

Basic — Write a first program

Definition: Programming is writing the list of instructions. I pick a language, write the steps in its words, run the program, and check the answer by hand. A first program is four lines long and does one small thing.

Types:

  • A program that adds two numbers.
  • A program that prints your name.
  • A program that finds the bigger of two numbers.

Uses: I use this when I start anything new. I write the smallest program that does the job, run it, and check it before I add more.

Dimensions: One program, a few lines, one user: me. What breaks first is a typing mistake, and I notice it because the program will not run at all. It costs minutes to write a first program. It costs hours when I try to write a big one before I can write a small one. The trade is simple: small and working beats big and broken.

Intermediate — Reading errors and fixing them

Definition: At this level I read error messages instead of fearing them. The message names the line and the problem. I fix one thing, run again, and check the answer. I keep the version that works before I try to make it better.

Types:

  • Typing errors: a missing bracket, a misspelled name.
  • Logic errors: the program runs and gives a wrong answer.
  • Errors that stop the program: it cannot go on past the bad line.

Uses: I use this every day. I write a little, run it, read the message, fix one thing. The loop is the work.

Dimensions: A program of hundreds of lines. What breaks is the line I changed last, and I notice it because the program worked before that change. It costs patience to change one thing at a time. The trade is that one change at a time tells me what fixed it, and five changes at once tell me nothing.

Advanced — Finding bugs you cannot see

Definition: At this level the program runs and gives a wrong answer with no error. I find the bug by reading the list with real numbers, line by line, until one line gives a value I did not expect. I add small checks that print values while the program runs, so I can see what it is doing.

Types:

  • Wrong values: the program works on a number that went wrong earlier.
  • Off-by-one errors: the program does something one too many or one too few times.
  • Wrong order: two steps that must run in one order run in the other.

Uses: I use this when the program runs clean and the answer is wrong. I trace the list with real numbers instead of guessing.

Dimensions: A program of thousands of lines, written by more than one person. What breaks is the step nobody traced, and I notice it when the answer is wrong but nothing looks broken. It costs time to trace a list by hand. The trade is that tracing finds the bug, and guessing does not.

The off-by-one bug. The most common bug in a loop is stopping one step too early or one step too late. I wrote a total that skipped the last price. The program ran fine. It printed a wrong number with total confidence. That is what makes this bug dangerous. Nothing crashes. The answer is just wrong.

$ python3 -c "
def total(prices):
    s = 0
    for i in range(len(prices) - 1):
        s += prices[i]
    return s
print('buggy total:', total([10, 20, 30]))"
buggy total: 30

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, and it will fail on the first line of code.
  • One more flag worth knowing: 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. It prints the same object, spread over lines.

Try it: run the code above. The right answer is 60. The program says 30. Now change the loop to for p in prices: and add s += p. Run it again. It prints 60. The fix is one line. Finding it is the skill.

A program that trusts its input will crash on it. A user types text where a number should go, and the program dies. I never trust input. I check it first, and I say what is wrong in plain words. A program that rejects bad input politely is a program that stays up.

$ python3 -c "
raw = 'abc'
try:
    n = int(raw)
    print('got', n)
except ValueError:
    print('reject: expected a number, got', repr(raw))"
reject: expected a number, got 'abc'

Try it: change raw to '42' and run it again. It prints got 42. The same code accepts good input and rejects bad input. That is the whole trick. Check first, then use.

Master — Programs other people use

Definition: At this level my program runs for other people, on machines I do not own, and it must not break when they use it in ways I did not expect. I test it with strange inputs. I handle errors instead of crashing. I write down what the program does, so the next person can fix it without me.

Types:

  • Tests: small programs that check my program with known answers.
  • Error handling: the program says what went wrong instead of stopping silently.
  • Documentation: words that tell the next person what the program does and why.

Uses: I use this when a program leaves my laptop and meets real users. I test it with inputs I did not plan for, because users will provide them.

Dimensions: Many users, many inputs, one program that must keep working. What breaks is the input I never tested, and I notice it when a user reports a wrong answer I cannot reproduce. It costs real effort to test and document. The trade is that the effort costs hours, and a program that breaks for users costs trust.

Slow code at scale. A loop that is fast on ten items can be slow on a million. I measure before I guess. The time command shows how long a program really took, and that number beats any feeling about which way is faster.

$ time python3 -c "
s = 0
for i in range(1000000):
    s += i
print(s)"
499999500000

real    0m0.154s

Every flag in the commands above, letter by letter.

  • time is a shell keyword, not a program. It runs the command after it and reports three numbers. real is wall clock time. user is time the CPU spent on my code. sys is time the CPU spent on the system doing work for my code.
  • One more flag worth knowing: time -p prints the same three numbers in plain POSIX format, one per line. A script can read that format. The default format is for my eyes only.

Check it: run time python3 -c "print(sum(range(1000)))", then the same line with time -p in front. The numbers match. The layout does not.

Try it: run the timing above, then time the built-in way with time python3 -c "print(sum(range(1000000)))". It takes about 0.044s. Compare the two real times. The built-in wins by a lot. At small sizes the difference does not matter. At a million items it does.

A program that never finishes. A loop with no exit runs forever, and a program that runs forever looks exactly like a program that is working hard. I put a limit on it. The timeout command kills a program after a set number of seconds, and its exit code tells me it was killed.

$ 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. TERM asks the program to stop. A program that listens stops cleanly.
  • echo $? prints the exit code of the last command. 124 means timeout had to kill it. 0 means it finished on its own. I read $? right after the command, because the next command overwrites it.
  • One more flag worth knowing: timeout -k 5 sends KILL 5 seconds after TERM. KILL cannot be ignored. Without -k, a program that ignores TERM runs forever.

Check it: run timeout 2 python3 -c "while True: pass"; echo $?. It prints 124. Then run timeout -k 2 1 python3 -c "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(30)"; echo $?. The program ignores TERM, so KILL arrives 2 seconds later, and the code is 137.

Try it: run the command above. It takes two seconds, then stops. Exit code 124 means timeout killed it. Without timeout, that program would still be running. Every long job I run gets a timeout, so a stuck job fails loudly instead of running all night.

Go deeper

A language is a tool, not a religion. Python reads like plain words. JavaScript runs in every browser. Both turn into machine steps in the end. The list matters more than the language. Learn the list first and the language is just spelling.

The editor is not the program. The file is the program. The editor is the pen. You can write code in any text editor. The fancy ones help by pointing at mistakes early, and that help is worth having, but it is not the work.

Running often is the habit that separates beginners who finish from beginners who get stuck. Run after every small change. A program that worked a minute ago and breaks now broke because of the last change. That narrows the search to one place.

At 10x the size, the loop is the same. Write a little, run it, read the message, fix one thing. The only difference is that the program has more pieces, and you run the pieces one at a time.

At 100x, the loop is run by machines. Tests run the program thousands of times a day and report the failures. The loop never went away. It got automated.

a = 3
b = 4
answer = a + b
show answer

That is the whole first program, written in plain steps. Read it top to bottom. The first line stores 3. The second stores 4. The third adds them. The fourth shows 7.

Try it: find the missing 30. Run the buggy total from the Advanced section. It prints 30 for prices of 10, 20, and 30. The missing 30 is the last price. Fix the loop, run it again, and it prints 60. One line changed the answer by 30. That is why I test a program with numbers I can add in my head first.

$ python3 -c "
def total(prices):
    s = 0
    for i in range(len(prices) - 1):
        s += prices[i]
    return s
print('buggy total:', total([10, 20, 30]))"
buggy total: 30

One time it broke

What broke

A first program would not run. The error message named a line and said it did not know a name. The name was spelled two different ways in two places: total in one line, totla in the other. One letter, and the machine stopped.

Timeline

  • 14:20,I ran the program. It stopped with an error about a name it did not know.
  • 14:21,I read the message. It named the line. I looked at that line.
  • 14:22,the name on that line was totla. The name everywhere else was total.
  • 14:23,I fixed the spelling. I ran it again. The answer was 7.
  • 14:24,I saved the working version before I changed anything else.

What changed after

Two things. First, I read the error message before I touch the code. It names the line. Second, I run the program after every small change, so when it breaks I know the break is in the last change. A spelling mistake and a broken program look identical until you read the message.

If you remember nothing else

Design exercise

Write, in plain words, the list of instructions for a program that asks for your name and your age, then prints: "Hello, NAME. In 10 years you will be AGE." No code. Just the steps, in order.

Clarifying questions to ask

  • What is the input, and what is the output?
  • Which step adds 10 to the age, and which step builds the sentence?
  • What happens if the user types words instead of a number for the age?
  • What does the program do if the user types nothing for the name?
  • How would you test it? Give three inputs and the exact answers you expect.

Rough sizing

Start with the list. About six lines: ask for the name, ask for the age, add 10 to the age, build the sentence, show it, stop. The work is tiny. The CPU finishes it before you blink. The interesting part is not the size. It is the checks: what happens when the input is not what you expected.

Trade-offs to name

A short list is easy to read and breaks on strange input. A longer list with checks is harder to read and survives strange input. Checking the age costs one line and saves a crash. The trade is that every check costs a line, and it buys a program that does not fall over when a user types something unexpected.

Next in this series
Lesson F04 — Thinking in Steps: Programming Fundamentals & Logic Building