Quarry School

Choose a branch — quick review

In plain words

A footpath reaches a garden gate with a notice.

Rule

Write if, a condition and a colon. Indent the block beneath it, by four spaces in this course. Python runs the block only when the condition is true. An optional else: line, lined up with the if, has its own indented block, which runs only when the condition is false. Lines after the whole statement, back at the left margin, run in both cases.

Step

  1. Write the decision as two sentences, the first starting with if and the second with otherwise. The baggage rule invented for this lesson reads: if the bag is over the weight limit, charge a fee. Otherwise, charge nothing.

  2. Turn the first sentence into an if line. Write if, then the condition, then a colon: if weight > 23:.

  3. On the next lines, indented by four spaces, write what happens when the condition is True.

  4. If something different happens otherwise, write else: lined up with if, and indent its lines by four spaces too.

  5. Return to the left margin for the lines that run in both cases.

  6. Trace the program twice, once with a value that makes the condition True and once with a value that makes it False.

Trap

A line with the wrong indentation can still be a legal program. Take an if statement that has no else, and suppose its block should display two lines. Leave the second at the margin and Python reports no error. It treats that line as the first line after the if statement and runs it whatever the condition gave. Check the left edge of every line when a program does more than you expected.

When an else: follows, the same slip stops the program. A line at the margin ends the if statement, so the else: below it has no if to belong to, and Python reports a SyntaxError before any line runs.

A missing colon is caught before the program starts. if weight > 23 with no colon stops with a SyntaxError before any line runs, and the message marks the place in that line where Python found the problem.

Keep to four spaces for each level, and do not mix tabs with spaces. Start every statement of one block at the same depth. The blocks of statements nested inside it are indented further. A line whose depth fits no block stops the program with an IndentationError.