3.10. Python Control Flow Cheat Sheet#
For loops#
Use for loops to iterate over items in a list. The same code will run multiple times, with the loop variable changing each time the loop runs.
scores = [4, 6, 3] # we will iterate over this list
for score in scores: # this loop runs three times, with score changing
print(score) # on each loop, print what the score variable is currently
4
6
3
Use code within the for loop (indented under the for ... in ...: statement) to do something with the loop variable. For example, say we want to calculate a sum over all the items in a list.
total_score = 0 # to calculate a total, start at zero
for score in scores: # loop over all scores
total_score += score # add this score to the total
print(total_score)
13
Modifying a list#
Use for loops and append to make a new list from an existing list.
duration_s = [2250, 1400, 1820, 1970, 3880] # length of experiments in seconds
duration_h = [] # will hold length of experiments in hours
for dur in duration_s:
duration_h.append(round(dur / 3600, 2))
duration_h
[0.62, 0.39, 0.51, 0.55, 1.08]
List comprehensions#
Use list comprehensions to quickly create a list or make a modified copy of an existing list.
For example, say we want to generate standard subject identifiers of the form sub-XXX. First, let’s see how we can use a normal for loop to do this. The :03d is a format specifier that indicates we want to take the number (e.g., 1) and pad it with zeros to make it three digits (e.g., 001). We can use range(1, 6) to loop over the numbers 1 through 5.
subject_ids = []
for number in range(1, 6):
subject_ids.append(f"sub-{number:03d}")
print(subject_ids)
['sub-001', 'sub-002', 'sub-003', 'sub-004', 'sub-005']
Using a list comprehension, we can write the same thing more compactly.
subject_ids = [f"sub-{number:03d}" for number in range(1, 6)]
print(subject_ids)
['sub-001', 'sub-002', 'sub-003', 'sub-004', 'sub-005']
To exclude some items from your list, use an if statement with the not and in operators (in checks if an item is somewhere in a list).
excluded = [2, 5] # subject numbers 2 and 5 should be excluded
subject_ids = [f"sub-{number:03d}" for number in range(1, 6) if number not in excluded]
print(subject_ids)
['sub-001', 'sub-003', 'sub-004']
List comprehensions can also be used to make a modified copy of an existing list. Here, we take the list of subject identifiers we just made and get just the numeric part, without the "sub-" part. First, let’s see how this works if we use a standard for loop.
subject_codes = []
for id in subject_ids:
subject_codes.append(id.split("-")[1])
print(subject_codes)
['001', '003', '004']
We can write the same thing using a list comprehension instead.
subject_codes = [id.split("-")[1] for id in subject_ids]
print(subject_codes)
['001', '003', '004']
Using counters with loops#
To calculate a total over items in a list, use a counter with a for loop. Use len to get the total number of items in a list.
ages = [23, 26, 20, 25, 22, 21]
total = 0
for age in ages:
total += 1
mean_age = total / len(ages)
mean_age
1.0
To calculate a mean of some measure, take the total and divide by the number of observations.
Looping over multiple lists#
Use the zip function to iterate over two or more lists simultaneously.
total_combined = 0
scores_test1 = [4, 3, 7] # scores for each participant from test 1
scores_test2 = [8, 2, 5] # corresponding scores for test 2
for score1, score2 in zip(scores_test1, scores_test2):
total_combined += score1 + score2 # add the two scores for this participant
mean_combined = total_combined / len(scores_test1)
print(mean_combined)
9.666666666666666
Using conditionals with loops#
Use a combination of for loops and if statements to perform more complicated calculations, such as filtering out invalid data.
response_times = [0.83, 0.92, 1.24, 0.97, 0.65, 0.22] # response times in seconds
total_included = 0 # total of included times so far
n_included = 0 # number of included trials so far
for rt in response_times:
if rt >= 0.3: # exclude trials with response times less than 0.3 s
total_included += rt
n_included += 1
mean_included = total_included / n_included
Exceptions#
Exceptions are used to indicate when something unexpected has happened that makes it difficult or impossible to run a program normally.
When writing a function, use the raise keyword with an error function to indicate when your program identifies that something is wrong.
def generate_id(number):
if number < 1:
raise ValueError("Number must be greater than zero.")
id = f"sub-{number:03d}"
return id
Use the error function that best fits the case you are testing for. Common error types are ValueError (an input to a function has an inappropriate value), TypeError (an input has an inappropriate data type), and RuntimeError (other unexpected problems).
print(generate_id(2))
print(generate_id(100))
# generate_id(0) # will raise an exception and halt code execution
sub-002
sub-100
When calling a function, use a try/except block to avoid crashing your program, and do something else instead.
number = 0
try:
id = generate_id(number) # try to run this...
except:
id = None # run this if there is an exception
print(id)
None