局部变量' output_file'以前引用过,这段代码几周前工作了,现在它不起作用怎么可能呢?

时间:2017-09-16 01:14:01

标签: python file-io

这件事很难在内部发布代码和上下文     #This是一个菜单驱动的乘法游戏。我正在努力拯救高潮     #score在一个名为multiplication_game.txt ...

的文件中
def single_player():
    in_file = open('multiplication_game.txt', 'r')
    highest_times_selection = int(in_file.readline())
    print('\n____now lets see how u do on the times tables____')
    correct = 0
    missed = 0


times_selection = int(input(
'\nPlease enter a times time table integer to practice: '))

#This simple generates the multiplation questions and checks for right or 
#wrong.

for number in range(0,11):
    print(times_selection, 'x' , number, '=')
    user_answer=int(input('answer: '))
    correct_answer = times_selection * number

if user_answer == correct_answer:
    correct+=1
else:
    missed+=1

#This is where if its a perfect score and a high times table than the 
#previous saved score it should be opened and the new score saved in the 
#text document.  

if missed == 0 and times_selection > highest_times_selection :
    output_file = open('multiplication_game.txt', 'w')
    name = input('You have the highest Score!!\n enter your name: ')
    output_file.write(str(times_selection)+ '\n')
    output_file.write(name + '\n')
else:
    print('you missed ', missed, 'and got', correct,'correct\n')
    output_file.close()

2 个答案:

答案 0 :(得分:0)

在分配colorscheme tomorrow-night-eighties set background=dark set colorcolumn=100 highlight ColorColumn ctermbg=darkgrey set nowrap set number 之前尝试定义它。

提示:在您上次output_file = None条件之前。

答案 1 :(得分:0)

这看起来像是家庭作业,所以我不想给你答案,而是引导你去做。

看一下你的高分表的if / else,然后两次遍历你的代码,每次到达这个位置时选择一个不同的分支(if / else的不同部分)。在定义它们时在纸上写下变量名称,每次走过时都会从一张新纸上开始。如果您访问变量,请在列表中进行检查。如果您尝试访问列表中不存在的变量,则它与python说aa相同 - 您在定义它之前尝试访问它。

希望这有助于解决您的问题并在将来学习如何调试。