错误原因:在函数外部已经定义了变量correctnum,在函数内部对该变量进行运算,运行时会遇到了这样的错误:
主要是因为没有让解释器清楚变量是全局变量还是局部变量。
correctnum=0 #答对题目数量
def main():
for i in range(totalnum): # 循环遍历问题列表
ask_Q(i,Q_list[i]['question'])
for j in range(len(Q_list[i]['choices'])):
print("{0}.{1}".format(to_letter(j),Q_list[i]['choices'][j]))
correctnum=correctnum+answer(Q_list[i]['answer'])#错误
print("共{0}题,答对{1}题,正确率为{2}%".format(totalnum,correctnum,(correctnum/totalnum) * 100))
解决方法:
第一种,当全局变量来看,就是使用global关键字,在函数内部先声明a这个变量是全局变量。
correctnum=0 #答对题目数量
def main():
global correctnum # 为了解决这个错误,UnboundLocalError: local variable 'correctnum' referenced before assignment,使用global让解释器清楚变量是全局变量还是局部变量
for i in range(totalnum): # 循环遍历问题列表
ask_Q(i,Q_list[i]['question'])
for j in range(len(Q_list[i]['choices'])):
print("{0}.{1}".format(to_letter(j),Q_list[i]['choices'][j]))
correctnum=correctnum+answer(Q_list[i]['answer'])
print("共{0}题,答对{1}题,正确率为{2}%".format(totalnum,correctnum,(correctnum/totalnum) * 100))
第二种是当局部变量。就是这个变量只在函数内使用,那么只要在函数内把这个变量定义一下就行了