2017-09-16 18 views
-1

這個東西很難在裏面發佈代碼和上下文。
#這是一個菜單驅動的乘法遊戲。我正在attemtping保存高 #score在multiplication_game.txt命名的文件...之前引用的局部變量'output_file',這個代碼在幾個星期前工作,現在它不工作怎麼可能?

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() 
+0

你能重新張貼正確的縮進代碼嗎? – Bill

回答

0

嘗試的任何轉讓之前定義output_file = None

提示:在您最後的if-else條件之前。

+0

我試過這個,python會用名稱none來定義。我確實得到它的工作,雖然感謝您的幫助。 – needyPheonix

0

這看起來像家庭作業,所以我不想給你答案,而是引導你。

看看你的if/else是否爲你的高分表,並且遍歷你的代碼兩次,每次到達這個地方時採取不同的分支(if/else的不同部分)。在定義紙張時,記下紙張上的變量名稱,每次穿過時都會從新紙張開始。如果您訪問變量,請在列表中查看它。如果您嘗試訪問不在列表中的變量,則它與Python中的local variable referenced before assignment相同 - 您正在嘗試在定義它之前訪問它。

希望這有助於解決您的問題並學習如何在未來進行調試。

+0

不,我正在自己學習這個遊戲,只是我想出了一個遊戲。所以我想保持我的對象變量獨立,所以我知道何時讀取數據或寫入數據。我將input_file變量鎖定爲output_file,現在它工作。但我很困惑,因爲雖然我正在對output_file進行引用,但我也在爲它作出任務,爲什麼它沒有asignnment? 「open('textfile','w')」的賦值是否正確?謝謝你的幫助。 – needyPheonix

+0

是的,分配是正確的,問題是_when_你訪問它。達到output_file定義的唯一方法是,如果你已經碰巧進入了高分表,即達到了你的第一個if/else分支(這可能在你的代碼中)。如果你還沒有打開它,嘗試關閉'else'中的output_file會產生兩個問題:1)你還沒有定義變量,所以它找不到要關閉的文件,2)即使你定義了' output_file = None'之外的if/else,它仍然無法關閉該文件,因爲該變量中沒有一個。 – kdd

+0

您的選擇是在完成寫入之後立即打開**和**關閉文件,或者在到達if/else之後打開它並關閉它。 – kdd

相關問題