2017-09-16 3 views
-1

이 코드는 내부에 코드와 컨텍스트를 게시하기가 어렵습니다.
#이 메뉴를 이용한 승산 게임입니다. 난 ... multiplication_game.txt라는 이름의 파일에의 할당하기 전에 output_file = None을 정의하는로컬 변수 '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

시도를 높은 #score을 저장 attemtping하고있다.

팁 : 이전에 if-else 상태입니다.

+0

나는 이것을 시도했다, 파이썬은 이름이 정의되지 않은 이름으로 응답 할 것이다. 나는 너의 도움을 위해 고맙지 만 일하게했다. – needyPheonix

0

이것은 숙제 인 것처럼 보이므로 답을주고 싶지는 않지만 오히려 당신을 이끌어 가고 싶습니다.

높은 점수 테이블에 대해 if/else를 살펴보고이 지점에 도달 할 때마다 다른 지점 (if/else의 다른 부분)을 두 번 통과하는 코드를 두 번 살펴보십시오. 변수 이름을 정의 할 때마다 종이에 변수 이름을 적어두고 걸을 때마다 새 용지를 사용하여 다시 시작하십시오. 변수에 액세스하는 경우 목록에서 변수를 확인하십시오. 목록에없는 변수에 접근하려고하면, 파이썬이 local variable referenced before assignment을 말하는 것과 같습니다. 정의하기 전에 액세스하려고합니다.

희망 사항은 문제를 파악하고 앞으로 디버그하는 방법을 배우는 데 도움이됩니다.

+0

아니, 나 혼자서 이걸 배웠어. 그래서 나는 데이터를 읽거나 데이터를 쓰는 순간을 알기 위해 객체 변수를 별도로 유지하려고했습니다. input_file 변수를 output_file에 지정했는데 이제 작동합니다. 하지만 나는 output_file에 대한 참조를 만들고 있지만 혼란 스러울뿐만 아니라 그것에 대한 할당도하고 있는데, 왜 그것이 asignnment를 말하지 않는가? "open ('textfile', 'w') '은 할당이 정확합니까? 당신의 도움을 주셔서 감사합니다. – needyPheonix

+0

예. 과제가 정확합니다. 문제는 귀하가 접근 할 때입니다. output_file의 정의에 도달하는 유일한 방법은 이미 높은 점수 표에 들어간 경우, 즉 처음 if/else 분기 (코드에서 가능)에 도달 한 경우입니다. 'else' 파일의 output_file을 아직 닫지 않은 상태에서 닫으려고하면 다음과 같은 두 가지 문제가 발생합니다. 1) 아직 변수를 정의하지 않았으므로 닫을 파일을 찾을 수 없습니다. 2) output_file = None'이 if/else 외부에 있기 때문에 변수에 파일이 없기 때문에 파일을 닫을 수 없습니다. – kdd

+0

옵션은 여기에서 ** 열면 ** 파일을 닫은 후 파일을 닫거나 파일을 열 때마다 파일을 닫은 다음 닫을 수 있습니다. – kdd