This is a simple code I wrote for the flanker task:
import random
congruent = open('congruent.txt', 'r')
incongruent = open('incongruent.txt', 'r')
def createList(file):
lst = []
for row in file:
lst.append(row.strip('\n'))
return lst
file.close()
lstCongruent = createList(congruent)
lstIncongruent = createList(incongruent)
nr_trials = 20
def middleString(txt):
middle = txt[(len(txt)-1)//2]
return middle
def checkCongruency(item):
if item in lstCongruent:
correctCongruentAnswers = 0
correctCongruentAnswers = 1
return correctCongruentAnswers
elif item in lstIncongruent:
correctIncongruentAnswers = 0
correctIncongruentAnswers = 1
return correctIncongruentAnswers
for i in range(nr_trials):
rndItem = random.choice(lstCongruent lstIncongruent)
print(rndItem)
answer = input('Please write your answer: ')
if answer == 'STOP':
exit()
while answer != 'F' and answer != 'J':
print('\33[91m Please type only F or J \33[0m')
break
if middleString(rndItem) == '<' and answer == 'F':
print('Correct answer!')
checkCongruency(rndItem)
elif middleString(rndItem) == '>' and answer == 'J':
print('Correct answer!')
checkCongruency(rndItem)
else:
print('Incorrect answer')
print('Correct congruent answers: ', correctCongruentAnswers)
print('Correct incongruent answers: ', correctIncongruentAnswers)
But when I run it, I get:
File "main.py", line 68, in <module>
print('Correct congruent answers: ', correctCongruentAnswers)
NameError: name 'correctCongruentAnswers' is not defined
is there any way to solve this without completely changing the code? I've tried different things, like defining the functions inside the for loop or some other stuff, but it won't work.
CodePudding user response:
Variables inside the function won't exist in the main script. If you wish to use the correctCongruantAnswers
from the checkCongruency
function, you must create a new variable to receive this value when you run checkCongruency()
.
if middleString(rndItem) == '<' and answer == 'F':
print('Correct answer!')
congruency_result = checkCongruency(rndItem)
elif middleString(rndItem) == '>' and answer == 'J':
print('Correct answer!')
congruency_result = checkCongruency(rndItem)
else:
print('Incorrect answer')
CodePudding user response:
Since variable inside functions can only be use within the function, you can declare them as being global variables, albeit this is not good practice.
def checkCongruency(item):
global correctCongruentAnswers #here
global correctIncongruentAnswers #and here
if item in lstCongruent:
correctCongruentAnswers = 0
correctCongruentAnswers = 1
return correctCongruentAnswers
elif item in lstIncongruent:
correctIncongruentAnswers = 0
correctIncongruentAnswers = 1
return correctIncongruentAnswers