Control flow: conditions and loops
The only two moves a program has: choosing a path with boolean algebra, and repeating a path until the data or the condition says stop.
A program that only stores values does nothing. It becomes useful at the moment it starts choosing: if the cart is empty, show the empty message; for every row in the file, add up the price. Those are the only two moves a program has. Conditions pick a path. Loops repeat a path. Every algorithm you will ever write is built from those two moves, nested inside each other.
In logic:1 you wrote expressions like not paid, paid and age >= 18, paid or free. Those were abstract. In code they are exactly the same expressions, and if is the machine that turns one of them into an action.
logic:1 code
not paid --> !paid
paid and age >= 18 --> paid && age >= 18
paid or free --> paid || free
if (paid && age >= 18) { ... }Same boolean algebra, two spellings. The operator names change, the truth tables do not.Here is the same decision in all three languages: is this person an adult?
if age >= 18:
label = "adult"
else:
label = "minor"Python: a colon, and indentation instead of braces.let label;
if (age >= 18) {
label = "adult";
} else {
label = "minor";
}JavaScript: braces around the body, semicolons at the end.var label string
if age >= 18 {
label = "adult"
} else {
label = "minor"
}Go: braces, and the condition goes without parentheses.Loops come in two flavours and picking the right one is most of the skill. A for loop repeats once per item of a known collection, and something else decides when it stops. A while loop repeats as long as a condition stays true, and you decide when it stops by changing something inside the body.
for item in list: once per item, list decides how many
while needed: while the condition stays true, repeat
for i in range(3): 3 rounds
while retries < 3: up to 3 rounds, or fewer if it succeeds earlyA for loop counts what it was given. A while loop counts itself, and can get that wrong.The same for loop in three languages: add up a list of scores.
total = 0
for score in scores:
total = total + scorePython: for over the list directly, no index needed.let total = 0;
for (const score of scores) {
total = total + score;
}JavaScript: for of walks the values, not the positions.total := 0
for _, score := range scores {
total = total + score
}Go: range gives the position and the value, and Go insists that you do something with both.Now the loop that never ends, and why it happens. A while loop repeats while a condition is true. The condition is checked at the top of every round. If nothing inside the body ever changes the thing the condition tests, the condition stays true forever and the loop runs forever. The program is not broken. It is doing exactly what it was told, faithfully, until you close the tab.
while retries < 3:
print("trying")
trying
trying
trying
... and the tab never comes backThe condition retries < 3 is true on the first round. Nothing inside ever changes retries, so it is still true on the millionth.Remember Big-O from logic:1: count the steps as a function of how much data there is, and ignore whether the machine is fast. A loop is where that count is easiest to see, because a loop over n items does its body n times.
for x in list: work * n O(n)
for i in range(n):
for j in range(n): work * n * n O(n^2)
n = 1000 O(n) ~1000 steps
O(n^2) ~1000000 stepsOne loop, n rounds. A loop inside a loop, n times n rounds.Practice
Look at the loop. What is the value of total after it finishes?
Hints
- Work out each round on paper: what is total before the round, and what does it become.
- The loop does not run when the condition is false before the first round, so check the starting value.
Here is a while loop that counts down from three. Put the rounds in the order they happen, finishing with the moment the loop stops.
- 1Check the condition again on the next round
- 2Leave the loop and continue with the next line of the program
- 3Run the body: print n and subtract one from n
- 4Check the condition n > 0 and find it true
- 5Check the condition and find it false, because n reached 0
Hints
- Nothing changes inside the loop body: the same few steps repeat, and only one of them ever changes the answer.
- A loop stops because the condition becomes false, and the condition can only become false if something inside the loop moves it.
Match each piece of code with the growth of its cost as the data grows. This is the Big-O idea from logic:1, seen from inside the loop.
Hints
- Compare the shape of the growth, not the exact number of steps: one extra row can mean one extra round, or n extra rounds.
- Two nested loops over the same list multiply, they do not add.