9 Solutions
9.2 Chapter 2. Variables, values and types
9.2.1 Exercise 1. Operators
= 2
x = 1.0
y print(x + y)
## 3.0
= 4.0
x = x + 1
y print(x + y)
## 9.0
x = 1
y = "1.0"
print(x + y)
= 4
x = 4.0
y print(x == y)
## True
= 12
x = x / 2
y print(y >= 5)
## True
9.2.2 Exercise 2. Values
Statements 2 and 4 are true
- Each value exclusively belongs to one data type
- Variables can be assigned any type of value
9.2.3 Exercise 3. Mini programs
= "1.0"
x = "1"
y print(x + y)
## 1.01
= 5
x = 2
y print((x / y) == 2.5)
## True
= 1
x = x + 1
x = x - 2
x print(x)
## 0
9.2.4 Exercise 4. Debugging
What goes wrong in the following code snippets?
x = 1
2x = 2
print(x + 2x)
- An illegal variable name is used
x = 3
y = "3"
print(x = y)
- The assignment operator is used instead of a comparative operator
name = "Colin"
print(This is + name)
- The content inside the brackets of the
print
statement lacks quotation marks
9.2.5 Exercise 5. String concatenation
- The statement ‘Veni, vidi, vici.’ was coined by Gaius Julius Caesar.
- The statement ‘Veni, vidi, vici.’, ‘I came, I saw, I conquered.’, was coined by Gaius Julius Caesar.
- The statement ‘Veni, vidi, vici.’ was coined by Gaius Julius Caesar, supposedly around 47 BC. Alternatively, it is also correct to say that the execution stops before the print statement due to the errornous string concatenation in the line before.
The
+
operator joins two strings, resulting in one string. The string at the left side of the operator precedes the string at the right side of the operator in the resulting string.myString = myString + s1 + s2 + year + s3
: the variableyear
is of typeint
which causes a TypeError during concatenation; integer objects and string objects cannot be concatenated. The error can be solved by either explicit typecasting or changing the variableyear
into a string to start with.
= myString + s1 + s2 + str(year) + s3
myString
= "47" year
9.2.6 Exercise 6. Variable names
-
2ndMan
: the variable name starts with a digit -
m@n3
: the@
signs is an illegal character -
man 5
: the space betweenman
and5
is illegal -
man_no._7
: the fullstop is illegal. Python will think thatman_no
is a class (which it is not by default) and therefore throw a NameError -
8thMan
: starting with a digit
9.2.7 Exercise 7. Stroop task welcome message
Note: The below description of what the specified code does is not expected from students. The intention is that they think about what happens internally in PyGame when implementing a task such as ‘printing something to the screen’.
= font.render(msgText,True,msgColor,BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,225)
text_rectangle.center screen.blit(text_surface,text_rectangle)
- Line 1 initializes a new Surface object with the pre-defined message
msgText
and colormsgColor
rendered on it and assigns it to the variabletext_surface
. PyGame draws text on a new Surface to create an image (Surface) of the text, then blit this image onto another Surface. - Lines 2 and 3 transform the surface to rectangular shape and specify the center of this rectangular shape in relation to the screen size of the program window.
- Line 4 copies the text Surface and position to the screen Surface, making it visible.
For further clarification, consult the PyGame documentation.
9.2.8 Exercise 8. Printing
= 52
participants = 200
trials = 3
experimental_sessions = trials * experimental_sessions
trials_pp = 4
conditions
= "easy/limited"
condition1 = "easy/unlimited"
condition2 = "difficult/limited"
condition3 = "difficult/unlimited"
condition4
print("In total,", participants, "participants participated in the study.")
## In total, 52 participants participated in the study.
print("A 2x2 factorial between-subjects design was employed.")
## A 2x2 factorial between-subjects design was employed.
print("The study examined the interaction of two independent variables: ")
## The study examined the interaction of two independent variables:
print("task difficulty (easy, difficult) and time (limited, unlimited).")
## task difficulty (easy, difficult) and time (limited, unlimited).
print(conditions, "conditions were devised, plus a control condition.")
## 4 conditions were devised, plus a control condition.
print("The conditions were:",condition1,",",condition2,",",condition3,"and",condition4)
## The conditions were: easy/limited , easy/unlimited , difficult/limited and difficult/unlimited
print("Participants were tested in", experimental_sessions, "experimental sessions.")
## Participants were tested in 3 experimental sessions.
print("Each session consisted of",trials,"trials.")
## Each session consisted of 200 trials.
print("In total, each partcipant thus completed", trials_pp, "trials.")
## In total, each partcipant thus completed 600 trials.
- Initially, the variable
trials
is a string. Multiplying the variable by three thus results in a string consisting of three times the value oftrials
. This can be fixed either by initializingtrials
as an integer or using explicit typecasting.
= int(trials) * experimental_sessions trials_pp
9.2.9 Exercise 9. Using Python as calculator
= 37
n1 = 456
n2 = 1027%n1
n3 = n2/n3
n2 += 4
n2 = n2%5
n4 -= 17
n4 = 65%n4/float(2)
n4
print(n4)
## -0.9285714285714306
9.2.10 Exercise 10. A Boolean puzzle
= 238
n1 = 17
n2
print(n1 > n2)
## True
print(n1/17 == 14)
## True
print(n1*n2/float(n1) == n2)
## True
print(n1+(-n1) == n2 - n2 and n1+(-n1) == 972%243 and n2-n2 == 0)
## True
print(n2*(n1*47/n2) == n1*47)
## True
print(n1/4 == n2/1*3 or n1/4 == n2/17*59)
## False
Hardcoded results are also valid, for example
print(n1+(-238) == n2 - 17 and n1+(-238) == 972%243 and n2-17 == 0)
Only for n1*n2/float(n1) == n2
hardcoding will not work.
9.3 Chapter 3. Conditionals
9.3.1 Exercise 1. Boolean logic
What is the output of the following code snippets?
= True
a = False
b
print(a and b)
## False
= True
a = False
b print(not a and b)
## False
= True
a = False
b print((not a) or b)
## False
= True
a = False
b
print(not (a and b))
## True
= True
a = False
b
print(not (a or b))
## False
= 1
a = 2
b = 4
c
print(a >= b and c > a + b)
## False
= 1
a = 2
b = 3
c
print(b % a >= c - (a + b))
## True
9.3.2 Exercise 2. State charts
# Variables
= "A"
STATE = 0
number_of_trials
while True:
#ITC
for event in pygame.event.get():
if STATE == "A":
= number_of_trials + 1
number_of_trials if event.type==KEYDOWN and event.key == K_SPACE:
= "C"
STATE elif STATE == "C":
if event.type==KEYDOWN and event.key == K_A or event.key == K_D:
= time()
arrival_at_B = "B"
STATE
#ATC
if STATE == "B":
if time() - arrival_at_B > 3:
if number_of_trials < 15:
= "A"
STATE else:
pygame.quit() sys.exit()
9.3.3 Exercise 3. Transition tables
For the following code snippet, make a transition table.
= "A"
STATE
while True:
#ITC
for event in pygame.event.get():
if STATE == "A":
= 0
count if event.type == KEYDOWN and event.key == K_w:
= "B"
STATE print(STATE)
elif STATE == "B":
= count + 1
count if event.type == KEYDOWN and event.key == K_a:
= time()
timer = "C"
STATE print(STATE)
elif STATE == "D":
if event.type == KEYDOWN and event.key == K_SPACE:
if count < 10:
= "B"
STATE else:
= "quit"
STATE print(STATE)
#ATC
if STATE == "C":
present_picture()if time() - timer > 3:
= "D"
STATE print(STATE)
elif STATE == "quit":
pygame.quit() sys.exit()
A | B | C | D | quit | |||
---|---|---|---|---|---|---|---|
FROM | A | w | |||||
B | a | ||||||
C | after 3s | ||||||
D | SPACE AND count < 10 | SPACE AND count >= 10 | |||||
quit |
9.3.4 Exercise 4. Mini programs
What is the output of the following mini programs?
= 5
x = 0
y
if x >= 5 and y != False:
print(y/x)
- Nothing
= 12
x
if x%3 == 0:
print("x is divisible by 3")
elif x%4 == 0:
print("x is divisible by 4")
x is divisible by 3
= 2
x = 0
y
if y + 1 == x or not x * 1 <= y:
print(x + y)
2
9.3.5 Exercise 5. Following the control flow
= "Hello, World!"
myString if len(myString) >= 13 or "ello" in myString:
= "Hi, programming aspirant!"
myString elif len(myString) <= 12 and "ello" in myString:
= "Hello, from the other side."
myString print(myString)
## Hi, programming aspirant!
if "Hi" in myString:
if len(myString) < 25:
= "Wow, my computer seems to answer!"
myString elif len(myString) > 25:
= myString + " -- Your computer"
myString else:
= myString + " How are you?"
myString else:
if len(myString) <= 29:
= "How are you, my computer?"
myString elif len(myString) == 27 and "Hello" in myString:
= myString + " I must have called a thousand times."
myString else:
= myString + " -- Adele"
myString print(myString)
## Hi, programming aspirant! How are you?
if "computer" in myString or len(myString) == 38 or "HI" in myString:
= myString + " I myself am doing fine."
myString else:
= myString + " I am doing just fine."
myString print(myString)
## Hi, programming aspirant! How are you? I myself am doing fine.
9.3.6 Exercise 6. Indentation
= 4
myNumber if myNumber < 20 and myNumber > 0:
if myNumber > 0 and myNumber < 15:
= myNumber + 3
myNumber else:
= myNumber - 3
myNumber print("This is a dead end statement.")
elif myNumber > 20:
print("This should only be printed if myNumber exceeds 20!")
else:
= 17 myNumber
9.3.7 Exercise 7. Pseudo code conditionals
1.
If not rain
if Jan has time
do swimming
else
do hiking
else
do read
2.
if age >= 18 and not alcohol abuse
set participation to True
3.
if rain
set wet to True
4.
if eligible
do briefing
if condition equals A
do lead to 001
else
do lead to 002
else
do explain
Number 3 is an example of the infamous Modus Ponens, where a condition a implies condition b. Whenever a is True
, b must also be True
.
Why is it so famous? Two reasons:
-
In mathematical proofs, a is called the sufficient condition for b, meaning that when a is True, b must be True as well. However, that does not exclude the possibility that b becomes True due to another condition c. For example:
When it rains the streets are wet
does not exclude the possibility that the street is wet because it has been washed with water.
In psychology of reasoning it has been shown that people have difficulties with checking the modus ponens. When asked to verify the above example, most people would first check whether the street is wet, although the most relevant question is whether it is raining, indeed.
9.3.8 Exercise 8. Modify Stroop Task
import pygame
import sys
from time import time
import random
from pygame.locals import *
from pygame.compat import unichr_, unicode_
##### VARIABLES #####
# Colors
= (250, 250, 250)
col_white = (0, 0, 0)
col_black = (220, 220, 220)
col_gray = (250, 0, 0)
col_red = (0, 200, 0)
col_green = (0, 0, 250)
col_blue = (250,250,0)
col_yellow
= 5
NTRIALS
= ("red", "green", "blue")
WORDS
= {"red": col_red,
COLORS "green": col_green,
"blue": col_blue}
= {"red": K_b,
KEYS "green": K_n,
"blue": K_m}
= col_gray
BACKGR_COL = (700, 500)
SCREEN_SIZE
pygame.init()
pygame.display.set_mode(SCREEN_SIZE) "Stroop Test")
pygame.display.set_caption(
= pygame.display.get_surface()
screen
screen.fill(BACKGR_COL)
= pygame.font.Font(None, 80)
font = pygame.font.Font(None, 40)
font_small
def main():
""" Start the Stroop task.
"""
## Variables
= "welcome"
STATE = 0
trial_number
# for gathering the response times
= []
RT
while True:
pygame.display.get_surface().fill(BACKGR_COL)
# Changing states by user input
for event in pygame.event.get():
# welcome screen --> prepare next trial (space bar)
if STATE == "welcome":
if event.type == KEYDOWN and event.key == K_SPACE:
= "prepare_next_trial"
STATE print(STATE)
# wait for response --> feedback (b, n, m)
elif STATE == "wait_for_response":
if event.type == KEYDOWN and event.key in KEYS.values():
# remember when the user has reacted
= time()
time_when_reacted # calculate the response time
= time_when_reacted - time_when_presented
this_reaction_time
RT.append(this_reaction_time)# was the response correct?
= (event.key == KEYS[this_color])
this_correctness = "feedback"
STATE print(STATE)
if event.type == QUIT:
= "quit"
STATE
# automatic state transitions
# prepare next trial --> wait for response (immediatly)
if STATE == "prepare_next_trial":
= trial_number + 1
trial_number # randomly pick word and color
= pick_color()
this_word = pick_color()
this_color # remember when stimulus was presented
= time()
time_when_presented = "wait_for_response"
STATE print(STATE)
# show feedback, then advance to next trial or goodbye (for 1s)
if STATE == "feedback" and (time() - time_when_reacted) > 1:
if trial_number < NTRIALS:
= "prepare_next_trial"
STATE else:
= "goodbye"
STATE print(STATE)
# Drawing to the screen
if STATE == "welcome":
draw_welcome()0]*1/4, 450, "Red: B", col_red)
draw_button(SCREEN_SIZE[0]*2/4, 450, "Green: N", col_green)
draw_button(SCREEN_SIZE[0]*3/4, 450, "Blue: M", col_blue)
draw_button(SCREEN_SIZE[
if STATE == "wait_for_response":
draw_stimulus(this_color, this_word)0]*1/4, 450, "Red: B", col_red)
draw_button(SCREEN_SIZE[0]*2/4, 450, "Green: N", col_green)
draw_button(SCREEN_SIZE[0]*3/4, 450, "Blue: M", col_blue)
draw_button(SCREEN_SIZE[
if STATE == "feedback":
draw_feedback(this_correctness, this_reaction_time)
if STATE == "goodbye":
draw_goodbye()
if STATE == "quit":
pygame.quit()
sys.exit()
pygame.display.update()
def pick_color():
""" Return a random word.
"""
= random.randint(0,2)
random_number return WORDS[random_number]
def draw_button(xpos, ypos, label, color):
= font_small.render(label, True, color, BACKGR_COL)
text = text.get_rect()
text_rectangle = (xpos, ypos)
text_rectangle.center
screen.blit(text, text_rectangle)
def draw_welcome():
= font.render("STROOP Experiment", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,150)
text_rectangle.center
screen.blit(text_surface, text_rectangle)= font_small.render("Press Spacebar to continue", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,300)
text_rectangle.center
screen.blit(text_surface, text_rectangle)
def draw_stimulus(color, word):
= font.render(word, True, COLORS[color], col_gray)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,150)
text_rectangle.center
screen.blit(text_surface, text_rectangle)
def draw_feedback(correct, reaction_time):
if correct:
= font_small.render("correct", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,150)
text_rectangle.center
screen.blit(text_surface, text_rectangle)= font_small.render(str(int(reaction_time * 1000)) + "ms", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,200)
text_rectangle.center
screen.blit(text_surface, text_rectangle)if reaction_time > 5:
= font_small.render("Come on, you can be faster!", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,250)
text_rectangle.center
screen.blit(text_surface, text_rectangle)
else:
= font_small.render("Wrong key!", True, col_red, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,150)
text_rectangle.center
screen.blit(text_surface, text_rectangle)#text_surface = font_small.render("Press Spacebar to continue", True, col_black, BACKGR_COL)
def draw_goodbye():
= font_small.render("END OF THE EXPERIMENT", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,150)
text_rectangle.center
screen.blit(text_surface, text_rectangle)= font_small.render("Close the application.", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,200)
text_rectangle.center
screen.blit(text_surface, text_rectangle)
main()
9.3.9 Exercise 9. Simplify nested conditionals
# participant details #
= 20
age = "Male"
gender = "Psychology"
study = True
speaks_Dutch = True
coffee = "not eligible for the experiment"
condition
## version 1
### The order of checking for study, coffee and
### language proficiency are interchangable
if age >= 18:
if study == "Psychology" or study == "Communication Sciences":
if coffee == True and speaks_Dutch == True:
if gender == "Female":
= "A"
condition else:
= "B"
condition else:
print("Participant is not eligible to take part in the experiment.")
else:
print("Participant is not eligible to take part in the experiment.")
else:
print("Participant is not eligible to take part in the experiment.")
## version 2
if age >= 18 and study == "Psychology" or study == "Communication Sciences" and coffee == True and speaks_Dutch == True:
if gender == "Female":
= "A"
condition else:
= "B"
condition else:
print("Participant is not eligible to take part in the experiment.")
9.4 Chapter 4. Lists
9.4.1 Exercise 1. Indexing
What is the output of the following code snippets?
= [6, 7]
a = [4, 5]
b
b.append(a)
print(b)
## [4, 5, [6, 7]]
= {1: 'a',
d 'a': 1}
print(d[1])
## a
= [1]
a = ('a', 2)
b
a.extend(b)
print(a[1])
## a
= (['a', 'd'], ['b', 'c'])
a, b
print(b[0])
## b
= [1, 2, 3]
a
print(a[-1])
## 3
= (1, 2, [3, 4], 5)
a
print(a[2][1])
## 4
9.4.2 Exercise 2. Debugging
Will the following code snippets throw an error? If anything goes wrong, why does it go wrong?
= 'Sigmund', 'Freud', (1856, 1939) a, b
## Error in py_call_impl(callable, dots$args, dots$keywords): ValueError: too many values to unpack (expected 2)
##
## Detailed traceback:
## File "<string>", line 1, in <module>
- A
ValueError
is thrown. There are too many values on the right side of the equals sign=
to unpack.
= [1, 2]
a = (3, 4)
b
a.append(b)print(a[3])
## Error in py_call_impl(callable, dots$args, dots$keywords): IndexError: list index out of range
##
## Detailed traceback:
## File "<string>", line 1, in <module>
- An
IndexError
is thrown. After appendingb
,a
has three elements.3
is not a valid index.
= ('a', [1, 2])
a
1].append(3) a[
- No error is thrown,
3
is appended to[1, 2]
.
= {('a', 'b'): 3}
a
print(a.keys())
## dict_keys([('a', 'b')])
- No error is thrown, the list of keys contains one element,
('a', 'b')
.
9.4.3 Exercise 3. Mini programs
What is the output of the following mini programs?
= {}
a
print(a.keys())
## dict_keys([])
[]
= []
a = ([1, 2], [3, 4], [5, 6])
b
a.extend(b)print(a[1])
## [3, 4]
[3, 4]
= ('a', ('b', 'c'))
a
print('b' in a)
## False
False
= [{'a': 1 }, {'a': 2}]
a
if 'a' in a[0]:
print(a[0]['a'])
elif 'a' in a[1]:
print(a[1]['a'])
## 1
1
9.4.4 Exercise 1. Shopping list
['buns', 'cheese', 'milk', 'oatmeal', 'blueberries', 'oranges', 'apples', 'chocolate', ['eggs', 'yoghurt', 'salmon'], ['icing sugar', 'whipping cream', 'lemons', 'flower', 'vanilla sugar', 'eggs', 'baking powder', 'margarine']]
9.4.5 Exercise 2. Dictionnaries
'Erik', 'Erikson', (1902, 1994))
('Theory of Cognitive Development',)
(1856
"Frederic"
"Skinner Box"
"positive reinforcement"
9.4.6 Exercise 3. Selecting elements
2]
shoppingList[0][0]
shoppingList["p3"][3]
grades["p5"][1]
grades["p6"][0]
grades["p1"][4][2]
grades["p5"][4][0]
grades["p6"][4][1] grades[
9.4.7 Exercise 4. Adjust a dictionnary data set
#1
'p1'][5] = 6.1
dataset['p7'][5] = 7.4
dataset[
#2
'p5'][0] = 23
dataset['p5'][1] = "Female"
dataset[
#3
'p4'][4][2] = True
dataset['p4'][4][3] = True
dataset[## or
'p4'][4] = [True,True,True,True,True]
dataset[
#4
'p2'][3] = "B-Health_Sciences"
dataset[
#5
'p4'].append("expelled")
dataset[## or
'p4'] = dataset['p4'] + ["expelled"]
dataset[
#final dataset
= {'p1':[21,"Female","Dutch","B-Psychology",[True,False,True,False,False],6.1],
dataset 'p2':[20,"Female","Dutch","B-Health_Sciences",[True,True,True,False,True],8.4],
'p3':[21,"Female","Dutch","B-Applied_Mathematics",[False,True,True,False,True],7.8],
'p4':[23,"Male", "German","B-Communication_Science",[True,True,True,True,True],8.8,"expelled"],
'p5':[23,"Female","Dutch","M-Business_Administration",[False,False,True,True,True],7.6],
'p6':[19,"Male","Swedish","B-Computer_Science",[True,False,False,True,False],7.5],
'p7':[19,"Male","German","B-Communication_Science",[True,True,False,True,True],7.4]
}
9.4.8 Exercise 5. A dictionnary data set
import numpy as np
= {'p1':("Male",19,"Dutch","Student"),
participants 'p2':("Male",47,"Dutch","Pharmacist"),
'p3':("Male",31,"Italian","PhD Student"),
'p4':("Female",22,"German","Student"),
'p5':("Female",46,"Dutch","Florist"),
'p6':("Male",27,"Dutch","Student"),
'p7':("Female",22,"Dutch","Police trainee"),
'p8':("Female",26,"Indian","Architect"),
'p9':("Male",18,"American","Student"),
'p10':("Male",20,"Chinese","Student")
}
""" Calculate the average age """
= (participants['p1'][1]+participants['p2'][1]+participants['p3'][1]+participants['p4'][1]+participants['p5'][1]+participants['p6'][1]+participants['p7'][1]+participants['p8'][1]+participants['p9'][1]+participants['p10'][1])/float(len(participants))
mean_age
# A more elegant, manual solution you will learn about in "Chapter 5. Loops"
# would be as follows:
= 0
age_sum for key in participants.keys():
+= participants[key][1]
age_sum = age_sum/float(len(participants))
loop_mean
# Using Numpy greatly simplifies calculations, but
# you first need to transform the data to fit your needs.
# You will see, however, that extracting the age variable and saving it
# separately will simplify other statistical operations later on.
= [participants['p1'][1],
age 'p2'][1],
participants['p3'][1],
participants['p4'][1],
participants['p5'][1],
participants['p6'][1],
participants['p7'][1],
participants['p8'][1],
participants['p9'][1],
participants['p10'][1]]
participants[
= np.mean(age)
numpy_mean
""" Calculate the standard deviation of the age variable """
= np.std(age)
std_age
""" Calculate the minimum and maximum of the age variable """
= np.nanmin(age)
minimum = np.nanmax(age) maximum
9.4.9 Exercise 6. Stroop extension
# -*- coding: utf-8 -*-
import pygame
import sys
from time import time
import random
from pygame.locals import *
from pygame.compat import unichr_, unicode_
##### VARIABLES #####
# Colors
= (250, 250, 250)
col_white = (0, 0, 0)
col_black = (220, 220, 220)
col_gray = (250, 0, 0)
col_red = (0, 200, 0)
col_green = (0, 0, 250)
col_blue = (250,250,0)
col_yellow = (250,0,127)
col_pink
= 5
NTRIALS
= ("red", "green", "blue", "yellow", "pink")
WORDS
= {"red": col_red,
COLORS "green": col_green,
"blue": col_blue,
"yellow": col_yellow,
"pink": col_pink}
= {"red": K_b,
KEYS "green": K_n,
"blue": K_m,
"yellow":K_v,
"pink":K_c}
= col_gray
BACKGR_COL = (700, 500)
SCREEN_SIZE
pygame.init()
pygame.display.set_mode(SCREEN_SIZE) "Stroop Test")
pygame.display.set_caption(
= pygame.display.get_surface()
screen
screen.fill(BACKGR_COL)
= pygame.font.Font(None, 80)
font = pygame.font.Font(None, 40)
font_small
= range(1,11)
p_numbers
= {"Stroop_3":[1,2,4,8,10],
conditions "Stroop_5":[3,5,6,7,9]}
def main():
""" Start the Stroop task.
"""
## Variables
= "welcome"
STATE = 0
trial_number # initialize participant number
= 0
p_number
# for gathering the response times
= []
RT
while True:
pygame.display.get_surface().fill(BACKGR_COL)
# Changing states by user input
for event in pygame.event.get():
# welcome screen --> prepare next trial (space bar)
if STATE == "welcome":
if event.type == KEYDOWN and event.key == K_SPACE:
= "enter_participant_number"
STATE print(STATE)
# wait for response --> feedback (b, n, m)
elif STATE == "wait_for_response":
if event.type == KEYDOWN and event.key in KEYS.values():
# remember when the user has reacted
= time()
time_when_reacted # calculate the response time
= time_when_reacted - time_when_presented
this_reaction_time
RT.append(this_reaction_time)# was the response correct?
= (event.key == KEYS[this_color])
this_correctness = "feedback"
STATE print(STATE)
elif STATE == "enter_participant_number":
= prompt()
p_number = "transition_experiment"
STATE print(STATE + "\nRETURN TO PYGAME WINDOW")
elif STATE == "transition_experiment":
if event.type == KEYDOWN and event.key == K_SPACE:
= "prepare_next_trial"
STATE
if event.type == QUIT:
= "quit"
STATE
# automatic state transitions
# prepare next trial --> wait for response (immediatly)
if STATE == "prepare_next_trial":
= trial_number + 1
trial_number # randomly pick word and color
# depending on condition
if p_number in conditions["Stroop_3"]:
= pick_color()
this_word = pick_color()
this_color else:
= pick_color5()
this_word = pick_color5()
this_color # remember when stimulus was presented
= time()
time_when_presented = "wait_for_response"
STATE print(STATE)
# show feedback, then advance to next trial or goodbye (for 1s)
if STATE == "feedback" and (time() - time_when_reacted) > 1:
if trial_number < NTRIALS:
= "prepare_next_trial"
STATE else:
= "goodbye"
STATE print(STATE)
# Drawing to the screen
if STATE == "welcome":
draw_welcome()0]*1/6, 450, "Pink: C", col_pink)
draw_button(SCREEN_SIZE[0]*2/6, 450, "Yellow: V", col_yellow)
draw_button(SCREEN_SIZE[0]*3/6, 450, "Red: B", col_red)
draw_button(SCREEN_SIZE[0]*4/6, 450, "Green: N", col_green)
draw_button(SCREEN_SIZE[0]*5/6, 450, "Blue: M", col_blue)
draw_button(SCREEN_SIZE[
if STATE == "enter_participant_number":
draw_enter()
if STATE == "transition_experiment":
draw_transition()if p_number in conditions["Stroop_3"]:
0]*1/4, 450, "Red: B", col_red)
draw_button(SCREEN_SIZE[0]*2/4, 450, "Green: N", col_green)
draw_button(SCREEN_SIZE[0]*3/4, 450, "Blue: M", col_blue)
draw_button(SCREEN_SIZE[else:
0]*1/6, 450, "Pink: C", col_pink)
draw_button(SCREEN_SIZE[0]*2/6, 450, "Yellow: V", col_yellow)
draw_button(SCREEN_SIZE[0]*3/6, 450, "Red: B", col_red)
draw_button(SCREEN_SIZE[0]*4/6, 450, "Green: N", col_green)
draw_button(SCREEN_SIZE[0]*5/6, 450, "Blue: M", col_blue)
draw_button(SCREEN_SIZE[
if STATE == "wait_for_response":
draw_stimulus(this_color, this_word)if p_number in conditions["Stroop_3"]:
0]*1/4, 450, "Red: B", col_red)
draw_button(SCREEN_SIZE[0]*2/4, 450, "Green: N", col_green)
draw_button(SCREEN_SIZE[0]*3/4, 450, "Blue: M", col_blue)
draw_button(SCREEN_SIZE[else:
0]*1/6, 450, "Pink: C", col_pink)
draw_button(SCREEN_SIZE[0]*2/6, 450, "Yellow: V", col_yellow)
draw_button(SCREEN_SIZE[0]*3/6, 450, "Red: B", col_red)
draw_button(SCREEN_SIZE[0]*4/6, 450, "Green: N", col_green)
draw_button(SCREEN_SIZE[0]*5/6, 450, "Blue: M", col_blue)
draw_button(SCREEN_SIZE[
if STATE == "feedback":
draw_feedback(this_correctness, this_reaction_time)
if STATE == "goodbye":
draw_goodbye()
if STATE == "quit":
pygame.quit()
sys.exit()
pygame.display.update()
def prompt():
= 0
p_number while p_number == 0:
= int(raw_input("Please enter participant number here:"))
p_number if p_number in range(1,len(p_numbers)+1):
return p_number
else:
print("Unknown participant number, valid participant numbers are 1 to 10")
prompt()
def pick_color():
""" Return a random word.
"""
= random.randint(0,2)
random_number return WORDS[random_number]
def pick_color5():
""" Return a random word,
5 color Stroop version
"""
= random.randint(0,4)
random_number return WORDS[random_number]
def draw_button(xpos, ypos, label, color):
= font_small.render(label, True, color, BACKGR_COL)
text = text.get_rect()
text_rectangle = (xpos, ypos)
text_rectangle.center
screen.blit(text, text_rectangle)
def draw_welcome():
= font.render("STROOP Experiment", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,150)
text_rectangle.center
screen.blit(text_surface, text_rectangle)= font_small.render("Press Spacebar to continue", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,300)
text_rectangle.center
screen.blit(text_surface, text_rectangle)
def draw_enter():
= font_small.render("Please enter participant number in console", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,250)
text_rectangle.center
screen.blit(text_surface, text_rectangle)
def draw_transition():
= font_small.render("Press Spacebar to start the experiment", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,250)
text_rectangle.center
screen.blit(text_surface, text_rectangle)
def draw_stimulus(color, word):
= font.render(word, True, COLORS[color], col_gray)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,150)
text_rectangle.center
screen.blit(text_surface, text_rectangle)
def draw_feedback(correct, reaction_time):
if correct:
= font_small.render("correct", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,150)
text_rectangle.center
screen.blit(text_surface, text_rectangle)= font_small.render(str(int(reaction_time * 1000)) + "ms", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,200)
text_rectangle.center
screen.blit(text_surface, text_rectangle)else:
= font_small.render("Wrong key!", True, col_red, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,150)
text_rectangle.center
screen.blit(text_surface, text_rectangle)#text_surface = font_small.render("Press Spacebar to continue", True, col_black, BACKGR_COL)
def draw_goodbye():
= font_small.render("END OF THE EXPERIMENT", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,150)
text_rectangle.center
screen.blit(text_surface, text_rectangle)= font_small.render("Close the application.", True, col_black, BACKGR_COL)
text_surface = text_surface.get_rect()
text_rectangle = (SCREEN_SIZE[0]/2.0,200)
text_rectangle.center
screen.blit(text_surface, text_rectangle)
main()
9.5 Chapter 5. Loops
9.5.1 Exercise 1. Following the control flow I
What is the output of the following code snippets?
for i in range(len([1,2,3])):
print(i)
## 0
## 1
## 2
for i in range(len([])):
print(i)
= 0
a for i in range(3):
+= i
a print(a + i)
## 0
## 2
## 5
= 0
a = 30
b for i in range(5):
+= i
a -= i
b
print(a + b)
## 30
for i in range(1,3):
print(i)
## 1
## 2
= 10
i while i > 5:
print(i - 5)
-= 2 i
## 5
## 3
## 1
= 2
a = (1,2)
b
while a != 0:
for i in b:
print(a + i)
-= 1 a
## 3
## 4
## 2
## 3
9.5.2 Exercise 2. Debugging I
Do the following code snippets throw an error? If they do, what goes wrong? Only one answer is correct.
a = [4,6,8]
for i in len(a):
print(a[i])
The correct answer is:
- A
TypeError
is thrown because thefor
statement does not include a sequence to iterate over.
myNumber = 43
while True:
guess = input("Enter a number:")
if guess > 43:
print("My number is smaller than {0}".format(guess))
elif guess < 43:
print("My number is greater than {0}".format(guess))
else:
print("Ding, ding! Correct, my number is {0}".format(myNumber))
The correct answer is:
- No error is thrown, once the user guesses
43
,Ding, ding! Correct, my number is 43
will be printed, but the program does not terminate.
a = [4,6]
b = [0, 1.5]
for i in a:
for j in range(len(b)):
print(i * b[j])
The correct answer is:
- No error is thrown, the output is of the mini program is
0
,6.0
,0
,9.0
because each element ina
is multiplied by each element inb
.
9.5.4 Exercise 4. Following the control flow II
Disclaimer: It is possible that your Python interpreter returns the keys of dataset
in a different order than shown below when you execute dataset.keys()
on your system. This has to do with how dictionaries are stored internally in computer memory. Here as well hash functions are utilized for efficiency reasons. As a consequence, the order of the keys in a dictionary is unspecified (which is why you cannot use the index operator to access elements of a dictionary and p1
is not necessarily the first key shown in the list). It also means that when you display the keys of a dictionary as a list (which is what the keys()
method does), the order in which the keys occur in the list can differ from system to system. For you this means that you should not worry if your system returns a different order when you execute dataset.keys()
. But it is important that you understand why dataset[dataset.keys()[0]]
returns the value that is displayed when you execute the code snippet.
'p2', 'p3', 'p1', 'p6', 'p7', 'p4', 'p5', 'p10', 'p8', 'p9']
[20, 'Female', 'Dutch', 'B-Psychology')
(20, 'Female', 'Dutch', 'B-Psychology')
(20
5
4
21.8
19.75
9.5.5 Exercise 5. Debugging
= {'p1':(21,"Female","Condition B",[0.675,0.777,0.778,0.62,0.869]),
data 'p2':(20,"Female","Condition A",[0.599,0.674,0.698,0.569,0.7]),
'p3':(21,"Female","Condition A",[0.655,0.645,0.633,0.788,0.866]),
'p4':(23,"Male", "Condition A",[0.721,0.701,0.743,0.682,0.654]),
'p5':(20,"Male","Condition B",[0.721,0.701,0.743,0.682,0.654]),
'p6':(19,"Male","Condition B",[0.711,0.534,0.637,0.702,0.633]),
'p7':(19,"Male","Condition B",[0.687,0.657,0.766,0.788,0.621]),
'p8':(24,"Female","Condition A",[0.666,0.591,0.607,0.704,0.59]),
'p9':(23,"Female","Condition B",[0.728,0.544,0.671,0.689,0.644]),
'p10':(18,"Male","Condition A",[0.788,0.599,0.621,0.599,0.623])
}
= ("initialization",100)
fastest for participant in data:
= 0
RTsum for i in range(len(data[participant][3])-1):
+= data[participant][3][i]
RTsum = RTsum/len(data[participant][3])
RTmean if RTmean < fastest[1]:
= (participant,RTmean)
fastest
= ("initialization",0)
slowest for participant in data:
= 0
RTsum for RT in data[participant][3]:
+= RT
RTsum = RTsum/len(data[participant][3])
RTmean if RTmean > slowest[1]:
= (participant,RTmean)
slowest
= 0
all_mean = 0
all_sum = 0
number_of_trials for participant in data:
= 0
counter while counter < len(data[participant][3]):
+= data[participant][3][counter]
all_sum += 1
number_of_trials += 1
counter = all_sum/number_of_trials*len(data)
all_mean
print("fastest:", fastest)
print("slowest:", slowest)
print("all_mean:", all_mean)
9.5.6 Exercise 6. Nested loops
= [
participants "p1", ["Condition 1","Location A","withdrew","no audio"]),
("p2", ["Condition 1","Location A","no audio","no video"]),
("p3", ["Condition 2","Location B"]),
("p4", ["Condition 1","Location A","withdrew"]),
("p5", ["Condition 2","Location A"]),
("p6", ["Condition 2","Location B","withdrew"]),
("p7", ["Condition 1","Location A","no video"]),
("p8", ["Condition 1","Location B"]),
("p9", ["Condition 2","Location B","withdrew"]),
("p10",["Condition 1","Location A","withdrew"])]
(
= 0
counter for (participant,expInfo) in participants:
for info in expInfo:
if info == "withdrew":
+= 1
counter
print("The number of participants who withdrew their participation is", counter)
9.5.7 Exercise 7. Data transformation using loops
= [
participants "p1", ["Condition 1","Location A","withdrew","no audio"]),
("p2", ["Condition 1","Location A","no audio","no video"]),
("p3", ["Condition 2","Location B"]),
("p4", ["Condition 1","Location A","withdrew"]),
("p5", ["Condition 2","Location A"]),
("p6", ["Condition 2","Location B","withdrew"]),
("p7", ["Condition 1","Location A","no video"]),
("p8", ["Condition 1","Location B"]),
("p9", ["Condition 2","Location B","withdrew"]),
("p10",["Condition 1","Location A","withdrew"])]
(
= {}
dict_participants for participant in participants:
0]] = participant[1]
dict_participants[participant[
= 0
counterA = 0
counterB for key in dict_participants:
if dict_participants[key][1] == "Location A":
+= 1
counterA else:
+= 1
counterB
## or using nested loops
= 0
counterA1 = 0
counterB1 for key in dict_participants:
for info in dict_participants[key]:
if info == "Location A":
+= 1
counterA1 elif info == "Location B":
+= 1
counterB1
print("The number of participants who were tested at location A is", counterA, counterA1)
print("The number of participants who were tested at location B is", counterB, counterB1)
9.5.8 Exercise 8. Calculating a mean
import numpy as np
= range(1000)
seq = 0
counter sum = 0.0
while counter <= 999:
sum += seq[counter]
+= 1
counter
= sum/len(seq)
mean
print(mean, np.mean(seq))
9.5.9 Exercise 9. A guessing game
import random
import sys
= random.randint(0,1000)
number = 0
guesses
while(True):
try:
= input("Please enter a number between 0 and 1000")
user_input except SyntaxError:
sys.exit() if user_input == number:
print("Ding Ding Ding! Correct! The number was", number)
+=1
guesses print(guesses, "guesses needed")
break
elif user_input > number:
print("My number is smaller")
+=1
guesses elif user_input < number:
print("My number is larger")
+=1
guesses
sys.exit()
9.6 Chapter 6. Functions
9.6.2 Exercise 2. An imperfect list sorting attempt
-
Line 6/7. The
insert
function does not return the resulting list. -
Line 20 and 21. The output of the
swap
function is not assigned to any variable and thereby, the manipulation performed onmyList1
is not stored in memory. -
Line 22. Only two arguments are provided during the function call of
insert
. The function, however, requires three arguments: an element to be inserted, a position indicating where to insert the element, and a list into which the element is to be inserted. -
Line 25. The
swap
function is used incorrectly. First of all, the function only takes three arguments, but five arguments are provided. The person tried to swap several element pairs at once while the function is only suitable for swapping one pair at a time! - Line 25. Second, the order of the arguments provided to the swap function is messed up. The function first takes one element to be swapped, then the element with which the first element should be swapped and only then the list which contains the two elements.
-
Line 26. The
insert
function is as it is defined not suitable for appending elements at the end of a list. This can be solved in one of two ways: either, the function is left as is and instead of using insert, the built-in functionappend()
can be used. Or, and this makes the insertion function more robust, a check is added to the function, appending any element that is supposed to be inserted at a position that exceeds the index range of the list.
def insert(a,position,alist):
= copy.deepcopy(alist)
result if position >= len(result):
return result.append(a)
else:
return result[:position] + [a] + result[position:]
9.6.3 Exercise 3. An errorneous sorting algorithm
import copy
import random
def swap(a,b,alist):
= alist.index(a), alist.index(b)
index_a, index_b = index_b, index_a
index_a, index_b = copy.deepcopy(alist)
result = a,b
result[index_a], result[index_b] return result
def bubbleSort(alist):
= copy.deepcopy(alist)
result for iteration in range(len(result)-1):
for index in range(len(result)-1,0,-1):
if result[index] < result[index-1]:
= swap(result[index],result[index-1],result)
result return result
= range(51)
myList
random.shuffle(myList)print(myList)
print(bubbleSort(myList))
9.6.6 Exercise 6. Insertion sort algorithm
import copy
import random
def insertionSort(alist):
= copy.deepcopy(alist)
result for index in range(1,len(result)):
# Temporarily assign the element that is to be compared to the
# (sorted) sublist at the left of the element's position
= result[index]
value # Remember the position in the list of the element under investigation
= index
position
# Stepwise, compare each element left to the designated element (b) and the
# designated element (value). Whenever b is larger than value, update position
# by shifting the position of b to the current value of position, thus in fact,
# one place to the right. Continue until position equals 0 and there are no more elements b
# left to compare value to.
while position > 0 and result[position-1] > value:
= result[position-1]
result[position] -= 1
position
# Insert the value that has been compared to at the right position in the list
= value
result[position] return result
= range(51)
myList
random.shuffle(myList)
print(insertionSort(myList))