[英]variable not defined even though it exists
这是我为侧卫任务编写的简单代码:
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)
但是当我运行它时,我得到:
File "main.py", line 68, in <module>
print('Correct congruent answers: ', correctCongruentAnswers)
NameError: name 'correctCongruentAnswers' is not defined
有没有办法在不完全更改代码的情况下解决这个问题? 我尝试了不同的东西,比如在 for 循环中定义函数或其他一些东西,但它不起作用。
方法中的变量不会存在于主脚本中。 如果您希望使用checkCongruency
correctCongruantAnswers
中的正确CongruantAnswers,则必须在运行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')
由于函数内部的变量只能在 function 中使用,因此您可以将它们声明为全局变量,尽管这不是好的做法。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.