Control flow

Up until this point, we’ve been using Python in quite a verbose way, often repeating the same lines of code with different inputs to get slightly different outputs.

For example, in Session 2’s section on Readable Code we created the following piece of code which calculates the pressure of an ideal gas at different volumes.

from scipy import constants

# Number of moles
n = 2

# Temperature in K
T = 298 

# Volumes in m^3
volumes = [10, 20, 30, 40, 50]

# Empty list of pressures
pressures = []

# Calculate pressure (Pa) at each temperature
# Using the ideal gas equation
pressures.append(n * constants.R * T / volumes[0])
pressures.append(n * constants.R * T / volumes[1])
pressures.append(n * constants.R * T / volumes[2])
pressures.append(n * constants.R * T / volumes[3])
pressures.append(n * constants.R * T / volumes[4])

Notice that the last five lines repeat what is essentially the same calculation. From Session 3, we know that each of these should be replaced by a call to a function, but this would still leave us with five lines of function calls. A better approach would be to somehow tell Python to repeat this command for many, slightly different, inputs.

In today’s Session, we’ll see how we can use control flow statements to express repetition and decision-making clearly and safely.