Rung 7
Python: syntax and types
Your first real language, and the discipline of saying what kind of thing you mean.
Best attempted after 2. Loops and branches and 3. Variables and state. Nothing stops you trying this now — the gate will tell you if you were right.
The gate
Write a terminal program that asks for input, branches on it, and does something useful. Then hand it to someone told to break it. It must not crash on empty input, on text where a number was wanted, or on the boundary value — and you must be able to say which type each variable holds at each point.
Nobody checks this but you. Do it honestly and the rungs above hold; do it loosely and they will not, somewhere further up where the cause is much harder to find.
Scratch made state visible by drawing it. Python makes you say it. The gap
between those two is mostly the discipline of types: a machine that will
happily add 2 + 2 and also "2" + "2" and give you 4 in one case and "22"
in the other is not being clever, it is doing exactly what you said.
Why this is on the ladder
Because from here to rung 48 you write code, and almost every confusing bug you
will hit is a type wearing the wrong hat. input() hands you text. A number
that came out of a file is text. A thing that looks like 5 on screen may be
5, 5.0, or "5", and those behave differently the moment you do arithmetic
or a comparison.
The habit worth building now is asking, at every line, what kind of thing is this? Later, at rung 44, the question becomes what shape is this array? — the same question, and the same class of bug.
Do this
Work through the first three chapters of Sweigart and write your own program as you go. A converter, a small quiz, a number-guessing game — the subject matters less than that it takes input and branches.
Then run it through Python Tutor and watch it execute one line at a time. This is rung 2's hand-tracing with the tracing done for you: same skill, and worth seeing done correctly a few times.
Now break it deliberately. Feed it nothing. Feed it "banana" where it wanted a
number. Feed it the exact boundary. Each crash is a place where you assumed a
type you never checked.
Where people get stuck
input() always returns text, so if answer == 5 is false even when the person
typed 5. It has to be int(answer) — which itself explodes on "banana", and
handling that is the actual work.
The other snag is = against ==. Rung 5 made the point that in algebra =
asserts sameness; in Python = assigns and == asks. Reading your code
aloud with those two words in place catches it faster than staring does.