Experimental Flow Control with Loops and Conditionals
Author
The structure of experiments has a certain flow: specific components must be executed repetitively a certain number of times and different things may have to happen depending on the state of the experiment. For example, an experiment may consist of multiple trials and depending on the response of the animal, we may or may not want to give a reward on any given trial. In this notebook we are going to explore the fundamental building blocks that allow us to translate this flow into code: loops and conditional expressions.
Section 1: Iterating trials
Many programs contain components that must be repeated a certain number of times, like trials in experiments. for loops allow us to do exactly - they repeat code for a certain number of times. They work on sequences of data, like lists, pull out one value after another and then do something with that value. This is very close to our everyday language: if you are throwing a party and inviting your friends, you are essentially executing a loop: for every person in the list of people I know: invite that person to the party.
| Code | Description |
|---|---|
for letter in ["a", "b", "c"]: print(letter) |
Print every letter in the list ["a", "b", "c"] |
for i in range(5): print(i) |
Print every number i between 0 and 5 (not including 5) |
for i in range(2, 7): print(i) |
Print every number i between 2 and 7 (not including 7) |
for i in range(1, 10, 2): print(i) |
Print eververy second number i between 1 and 10 (not including 10) |
for x_i in x: print(x_i) |
Print every element x_i in the collection x |
Exercises
Exercise: Write a for loop that prints the numbers 0 to 9.
Solution
for i in range(10):
print(i)0
1
2
3
4
5
6
7
8
9Exercise: Write a for loop that prints the numbers 5 to 10.
Solution
for i in range(5, 11):
print(i)5
6
7
8
9
10Exercise: Write a for loop that counts from 0 to 100 in steps of 10.
Solution
for i in range(0, 110, 10):
print(i)0
10
20
30
40
50
60
70
80
90
100Exercise: Use a loop to print each fruit in fruits with it’s color (for example "banana is yellow").
fruits = ["banana", "orange", "cherry"]
colors= ["yellow", "orange", "green"];Solution
for i in range(len(fruits)):
print(fruits[i] + " is " + colors[i])banana is yellow
orange is orange
cherry is greenExercise: Write a loop that prints the square of each number in numbers.
numbers = [4, 13, 56, 676]Solution
for number in numbers:
print(number ** 2)16
169
3136
456976Exercise: Write a loop that print out "Run experiment for animal n" for each animal id in animal_ids.
animal_ids = ["m23", "m59", "m145"]Solution
for aid in animal_ids:
print("Run experiment for animal " + aid)Run experiment for animal m23
Run experiment for animal m59
Run experiment for animal m145Exercise: Use a for loop within another for loop to print "This is block b" for each block in blocks and "This is trial t" for each t in trials.
blocks = [1, 2, 3]
trials = [1, 2, 3, 4, 5]Solution
for block in blocks:
print("This is block" + str(block))
for trial in trials:
print("This is trial" + str(trial))This is block1
This is trial1
This is trial2
This is trial3
This is trial4
This is trial5
This is block2
This is trial1
This is trial2
This is trial3
This is trial4
This is trial5
This is block3
This is trial1
This is trial2
This is trial3
This is trial4
This is trial5Section 2: Conditional Expressions
Another key component are conditional expressions. They allow us to write programs that behave differently under different circumstances. For example, under certain conditions in an experiment, you may want to give a reward or increase the difficulty of the task. An if statment can be accompanied by an else statement that tells the program what to do in case the if condition is not True. Additionally, the statement can have multiple elifs: other conditions that are only checked in case the if condition is not True. We could incorporate the if statement in our everyday example from the previous section and say: for every person in the list of people I know, if that person is a friend, invite that person to the party.
Reference Table
| Code | Description |
|---|---|
if x > 0: print("positive") elif x < 0: print("negative") else: print("zero") |
Prints whether the number x is "positive", "negative" or "zero" |
x in [1, 2, 3] |
Returns True if the value of x appears in the list [1,2,3] |
x==1 and y==0 |
Returns True both expressions are True (i.e. x is 1 AND y is 0) |
x==1 or y==0 |
Returns True if AT LEAST one expression is True |
not False |
Invert a boolean value (Returns: True) |
Exercise: Assign different values to x so that each print statement is executed once.
x = ...
if x > 10:
print("High positive number")
elif x > 0:
print("Small positive number")
elif x == 0:
print("Zero!")
elif x < -10:
print("Large negative number")
else:
print("Small negative number")Exercise: Modify the expression below by adding one elif statement to print("This is a string") when x is a string and one elif statement to print("This is a float") when x is a float. Assign different values to x so that each print statement is executed once.
x = ...
if isinstance(x, int):
print("This is an integer")
else:
print("I don't know what this is")Solution
for x in [1, "1", 1.0, [1]]:
if isinstance(x, int):
print("This is an integer")
elif isinstance(x, str):
print("This is a string")
elif isinstance(x, float):
print("This is a float")
else:
print("I don't know what this is")This is an integer
This is a string
This is a float
I don't know what this isExercise: Write an if/else statement that prints "long" when the list zeros is longer than 50 and "short" when it is shorter.
zeros = [0, 0, 0] *17;Solution
if len(zeros) > 50:
print("long")
else:
print("short")longExercise: Write an if/else statement to print"large value" if the absolute value of a variable x is larger than 10 (i.e. it is greater than 10 OR smaller than -10). Execute this statement while setting x to 5 and -13.
Solution
for x in [5, -13]:
if abs(x) > 10:
print("large value")
else:
print("small value")small value
large valueExercise: Use an if/else statement within a for loop to print("vowel") or print("consonant") for each letter in the list letters.
letters = ['w', 'q', 'x', 'k', 'g', 'm', 'f', 'i', 'w', 'j', 'h', 't', 'b', 'z', 'u', 'r', 'q', 'b', 'a', 'z']
vowels = ['a', 'e', 'i', 'o', 'u'];Solution
for letter in letters:
if letter in vowels:
print("vowel")
else:
print("consonant")consonant
consonant
consonant
consonant
consonant
consonant
consonant
vowel
consonant
consonant
consonant
consonant
consonant
consonant
vowel
consonant
consonant
consonant
vowel
consonantExercise: Use a for loop to iterate the list play_tone and an if/else statement to print("silence...") or print("beep") depending on whether the value in the list is True.
play_tone = [True, True, False, True, False, True, True, True];Solution
for t in play_tone:
if t is True:
print("beep")
else:
print("silence...")beep
beep
silence...
beep
silence...
beep
beep
beepExercise: Use a for loop and if/else statement to determine whether each number in numbers is odd or even.
numbers = [4, 18, 32, 13, 155, 56]Solution
for number in numbers:
if number % 2 == 0:
print(str(number) + " is odd")
else:
print(str(number) + " is even")4 is odd
18 is odd
32 is odd
13 is even
155 is even
56 is oddSection 3: Conditional Loops
We can also combine loops and conditionals and create a procedure that is repeatedly executed for as long as a certain condition is True.
This is exactly what while loops do. In an experiment, you may use them to wait while the subject is responding or to keep running the experiment until a certain finishing condition is met. Sticking to our party metaphor, we may say: while there are slices of pizza left, if you see a guest without pizza, offer them a slice of pizza.
Reference Table
| Code | Description |
|---|---|
while x>y: print("x is bigger") |
Prints "x is bigger" as long as x>y is True |
break |
Exit the current loop |
time.time() |
Get the current time |
time.sleep(1) |
Wait for one second |
Exercise: Run the cell below. Then, change the value of max_count to 500 and run it again. Finally, change True to False and run a third time.
max_count = 100
count = 0
while True:
count = count+1
if count >= max_count:
break
print("Ran " +str(count) +" iterations")Ran 100 iterationsSolution
max_count = 500
count = 0
while True:
count = count+1
if count >= max_count:
break
print("Ran " +str(count) +" iterations")
count = 0
while False:
count = count+1
if count >= max_count:
break
print("Ran " +str(count) +" iterations")Ran 500 iterations
Ran 0 iterationsExercise: Write a while loop that subtracts 1 from n_of_trials until it is 0.
n_trials = 100Solution
while n_trials > 0:
n_trials -= 1Exercise: Write a while loop that prints the same output as the for loop defined below.
for i in range(0, 10):
print(i)0
1
2
3
4
5
6
7
8
9Solution
i = 0
while i < 10:
print(i)
i += 10
1
2
3
4
5
6
7
8
9Section 4: Advanced Iteration
In some cases, we want to keep counting the number of iterations as we use a for loop to go through a list. This is what enumerate() does: it does not only return the elements in the sequence but also the number of each element in that sequence. Another useful tool is zip() which allows us to iterate through multiple sequences at once, for example: experimental conditions and stimulus intensities.
Reference Table
| Code | Description |
|---|---|
for x_i, y_i in zip(x, y): print(x_i, y_i) |
Prints every element x_i in x and every element y_i in y |
for i, x_i in enumerate(x): print(i, x_i) |
Print every element x_i and it’s index i in the list x |
Exercise: Write a for loop with zip() that prints each frequency and intensity in the lists frequencies and intensities.
frequencies = [600, 1000, 600, 1000]
intensities = [70, 70, 65, 65]Solution
for frequency, intensity in zip(frequencies, intensities):
print(frequency, intensity)600 70
1000 70
600 65
1000 65Exercise: Remove on element from frequencies to test what happens if the lists inside zip() do not have the same length.
Solution
frequencies = [600, 1000, 600]
intensities = [70, 70, 65, 65]
for frequency, intensity in zip(frequencies, intensities):
print(frequency, intensity)600 70
1000 70
600 65Exercise: Use a for loop with enumerate to print each element in conditions as well as the index of that element in the list.
conditions = ["a", "b", "a ", "b", "c", "c"]Solution
for i, condition in enumerate(conditions):
print(i, condition)0 a
1 b
2 a
3 b
4 c
5 cExercise: Use enumerate to iterate the list below and print out every second name.
names = ["Julia", "Matt", "Kyle", "Lisa"]Solution
for i, name in enumerate(names):
if i % 2 != 0:
print(name)Matt
LisaSection 5: BONUS: Puzzles
Even though the individual components we talked about are fairly simple, their interplay can produce a lot of complexity and allows us to achieve various things. This bonus section is intended to provide you with some challenging exercises that will put your knowledge of Python fundamentals to the test.
Exercise: Use for loops and if statements to find all prime number between 1 and 100.
Solution
for i in range(1, 101):
is_prime = True
for j in range(2, i - 1):
if i % j == 0:
is_prime = False
if is_prime:
print(str(i) + " is a prime number")1 is a prime number
2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
23 is a prime number
29 is a prime number
31 is a prime number
37 is a prime number
41 is a prime number
43 is a prime number
47 is a prime number
53 is a prime number
59 is a prime number
61 is a prime number
67 is a prime number
71 is a prime number
73 is a prime number
79 is a prime number
83 is a prime number
89 is a prime number
97 is a prime numberExercise: Create a while loop that shuffles the list until there are no immediate repetitions of the same element. Print the final list x.
import random
x = [1, 2, 3, 4, 5] * 10
random.shuffle(x) # randomize the list
print(x)[4, 5, 4, 1, 3, 4, 5, 4, 2, 4, 2, 4, 2, 2, 3, 3, 1, 3, 4, 4, 1, 2, 3, 2, 3, 5, 1, 3, 3, 1, 1, 5, 5, 5, 3, 2, 3, 2, 5, 2, 1, 1, 1, 1, 5, 2, 5, 4, 4, 5]Solution
ok = False
while not ok:
random.shuffle(x)
ok = True
for i in range(1, len(x)):
if x[i] == x[i - 1]:
ok = False
print(x)[1, 2, 4, 5, 3, 4, 3, 2, 4, 3, 2, 3, 5, 1, 5, 1, 4, 5, 2, 4, 3, 5, 4, 2, 1, 3, 4, 2, 5, 1, 5, 1, 5, 3, 2, 5, 3, 1, 2, 1, 2, 4, 1, 3, 4, 2, 5, 4, 1, 3]