Python 局部变量';输出文件';之前提到过,这段代码在几周前就已经运行了,现在它不工作了,这怎么可能呢?

Python 局部变量';输出文件';之前提到过,这段代码在几周前就已经运行了,现在它不工作了,这怎么可能呢?,python,file-io,Python,File Io,这东西很难在里面发布代码和上下文。 #这是一个菜单驱动的乘法游戏。我正试图拯救这个高地 #在名为multiplication\u 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 th

这东西很难在里面发布代码和上下文。
#这是一个菜单驱动的乘法游戏。我正试图拯救这个高地 #在名为multiplication\u 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()

尝试在任何赋值之前定义
output\u file=None


提示:在你最后一个
if-else
条件之前。

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

查看一下if/else的高分表,并在代码中遍历两次,每次到达此位置时都使用不同的分支(if/else的不同部分)。定义变量名称时,在纸上写下变量名称,每次浏览时都从一张新纸开始。如果您访问一个变量,请在列表中勾选它。如果您试图访问列表中没有的变量,这与python在赋值之前引用的
局部变量
是一样的——您试图在定义它之前访问它


希望这对解决您的问题和将来学习如何调试都有帮助。

您能用正确的缩进重新发布代码吗?不,我是自己学习的,只是一个游戏。所以我想把我的对象变量分开,这样我就知道我什么时候读数据或者写数据了。我将input_file变量转换为output_file,现在它可以工作了。但我很困惑,因为当我引用output_文件时,我也在为它赋值,为什么它会说no-asignment?“打开('textfile','w')”分配是否正确?谢谢你的帮助。是的,作业是正确的,问题是当你访问它时。它到达输出_文件定义的唯一方法是,如果您已经碰巧进入了高分表,即到达了第一个if/else分支(这在代码中是可能的)。如果尚未打开,尝试关闭
else
中的输出文件会产生两个问题:1)尚未定义变量,因此无法找到要关闭的文件;2)即使在if/else之外定义了
output\u file=None
,它仍然无法关闭该文件,因为该变量中没有文件。您可以选择在编写完文件后立即打开和关闭该文件,或者在到达if/else并在之后关闭它之前打开该文件。我尝试了此操作,python将以名称none not defined响应。不过我确实让它工作了,谢谢你的帮助。