Python Control Flow Cheatsheet#
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
Looping over indices#
Use range and len to loop over indices of a list.
print(range(3)) # use range to get a range of numbers
print(list(range(3))) # don't see the all numbers unless converted to a list first
range(0, 3)
[0, 1, 2]
for i in range(3):
print(i) # in a for loop, range will generate each number in the range
0
1
2
for i in range(len(scores)): # use len to get the number of items in a list
print(scores[i]) # each value of i is an index in scores
4
6
3
We can calculate the same total score as before, but now using indices to index into the scores list.
total_score = 0
for i in range(len(scores)):
total_score += scores[i]
print(total_score)
13
Looping using enumerate and zip#
Use the enumerate function to get both indices of a list and their corresponding items.
total_included = 0
for i, score in enumerate(scores):
if i >= 2: # exclude the first two trials
total_included += score # add to total if included
print(total_included)
3
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
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).
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']
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