Foundations: Python, Git and toolsLoading progress…

Conditions

Write a small program that transforms data using conditions, loops and functions.

Choosing a branch

So far every line ran. An if statement lets the program choose. It evaluates a condition, an expression that comes out True or False, and runs its indented block only when the condition is true. With elif and else you build a chain: Python checks the conditions from the top and runs the first block whose condition is true, then skips the rest.

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
if score >= 90:False, try the next one
elif score >= 80:True, so grade = "B"
elif score >= 70:never checked
else:never reached

grade is "B"

Only one branch ever runs. Drag across 90, 80 and 70: with >= the boundary value itself belongs to the higher grade.

Drag the score. Green is the branch that runs, red conditions were checked and failed, dashed ones were never looked at.

Indentation is part of the code

In Python the 4 spaces in front of a line are not decoration: they say which lines belong to the branch. A line at the left margin always runs; an indented line runs only when its condition holds.

score = 55
if score >= 70:
    print("passed")
    print("well done")       # inside the branch: skipped for 55

score = 55
if score >= 70:
    print("passed")
print("well done")           # not indented: prints for every score

Building conditions: comparing and combining

Comparisons are == (equal), !=, <, <=, > and >=. Combine booleans with and, or and not. The remainder operator % is handy for tests such as divisibility: year % 4 == 0.

a and bFalsetrue only when both are true
a or bTruetrue when at least one is true
not aFalseflips it
Flip a and b and watch the three operators.

Check yourself first

Predict first. With x = 3, which branch of if x >= 3: ... else: ... runs?

Predict first. The chain tests score >= 70 first, then elif score >= 90. What happens for a score of 95?

Chapter context

A program is a precise sequence of state changes. Python names refer to objects; reading a program means tracking the values those names refer to, rather than guessing from how the code sounds.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

For an accumulator over numbers x1,…,xnx_1,\ldots,x_n:

s0=0,si=si−1+xi.s_0=0,\qquad s_i=s_{i-1}+x_i.

The subscript denotes a step, not a Python index. After the last step, sns_n is the sum. For a mean, divide by the number of items, and define what should happen for an empty list.

Worked example

Trace a robot's forward distances [2, 1, 3]. Position starts at zero and changes to 2, then 3, then 6. Replacing three copy-pasted moves with a loop preserves the order and final state. A mean distance is 6/3 = 2; the count is 3, not the last list index 2.

Reference code

The following example uses the Python standard library and does not call a remote service.

moves = [2, 1, 3]
position = 0
for distance in moves:
    position += distance
assert position == 6
assert sum(moves) / len(moves) == 2

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

Assignment does not copy a mutable object. A loop stop value is exclusive. A function can return None even when its print output looks correct.