2012-04-22 2 views
0

함수에서 correct 변수를 이해하는 데 문제가 있습니다. correct 변수가 인덱싱되지 않으면 프로그램이 올바르게 작동하지 않습니다. 따라서 correct[0]. 그래서 내 질문에 왜 제대로 작동하지 않는 경우 그것은 색인이 생성되지 않습니다 그리고 정수가 subscriptable되지 않은 경우 심지어 색인을 생성 할 수 있습니다.파이썬에서 한 줄을 읽는 것이 왜 저 줄의 내용을 알려주지 않는 걸까요?

An Episode You Can't Refuse 
On the Run With a Mammal 
Let's say you turn state's evidence and need to "get on the lamb." /If you wait too long, what will happen? 
You'll end up on the sheep 
You'll end up on the cow 
You'll end up on the goat 
You'll end up on the emu 
1 
A lamb is just a young sheep. 
The Godfather Will Get Down With You Now 
Let's say you have an audience with the Godfather of Soul. /How would it be smart to address him? 
Mr. Richard 
Mr. Domino 
Mr. Brown 
Mr. Checker 
3 
James Brown is the Godfather of Soul. 

그리고 이것은 코드입니다 :

이 사용하는 텍스트 파일

이있다

# Trivia Time 
# Trivia game that reads a plain text file 

def open_file(file_name, mode): 
    """Open a file.""" 
    try: 
     the_file = open(file_name, mode) 
    except(IOError), e: 
     print "Unable to open the file", file_name, "Ending program.\n", e 
     raw_input("\n\nPress enter to exit..") 
     sys.exit() 
    else: 
     return the_file 

def next_line(the_file): 
    """Return the next line from the trivia file, formatted.""" 
    line = the_file.readline() 
    line = line.replace("/", "\n") 
    return line 

def next_block(the_file): 
    """Return the next block of data from the trivia file.""" 
    category = next_line(the_file) 

    question = next_line(the_file) 

    answers = [] 
    for j in range(4): 
     answers.append(next_line(the_file)) 

    correct = next_line(the_file) 
    if correct: 
     correct = correct[0] 

    explanation = next_line(the_file) 

    return category, question, answers, correct, explanation 

def welcome(title): 
    """Welcome the player and get his/her name.""" 
    print "Welcome to Trivia Challenge!\n" 
    print title, "\n" 

def main(): 
    trivia_file = open_file("trivia.txt", "r") 
    title = next_line(trivia_file) 
    welcome(title) 
    score = 0 
    # get first block 
    category, question, answers, correct, explanation = next_block(trivia_file) 
    while category: 
     # ask a question 
     print category 
     print question 
     for j in range(4): 
      print j + 1, "-", answers[j] 
     # get answer 
     answer = raw_input("What's your answer?: ") 
     # check answer 
     if answer == correct: 
      print "\nRight!", 
      score = score + 1 
     else: 
      print "\nWrong.", 
      print explanation 
      print "Score:", score, "\n\n" 
     # get next block 
     category, question, answers, correct, explanation = next_block(trivia_file) 
    trivia_file.close() 
    print "That was the last question!" 
    print "Your final score is:", score 

main() 
raw_input("\n\nPress the enter key to exit.") 
+0

"올바른 [0]"대신 "올바른"을 사용하면 어떤 방식으로 작동하지 않습니까? –

답변

6

correct = next_line(the_file) 후, correct'1\n' 같은 문자열입니다. correct[0]은 과 같은 문자열을 얻습니다. 나중에 raw_input의 결과와 비교하면 끝에 \n이 포함되지 않습니다. 따라서 첫 번째 문자를 꺼내려면 [0]을 수행해야합니다.

.strip()을 대신 사용하는 것이 좋습니다. 그 이유는 게임에 10+ 답변을 지원하도록 게임을 변경하거나 다른 종류의 이름을 사용하여 답변을 보내면 게임이 한 문자가 아닌 답변에 영향을 줄 수 있기 때문입니다. , 무슨 일이 일어나고 있는지 조금 더 분명 할 것입니다. 그리고 파일이나 사용자의 입력에서 명확히 관련이없는 끝 부분의 공백을 무시할 것입니다.

+0

권자, 잊어 버렸습니다. 고마워, 넌 멋져. –

+0

핑키 파이 : 답변 –

+2

+1을받는 것을 잊지 마세요. 추가 설명 :'correct'는이 값에 대한 좋은 이름이 아닙니다. 그것은 부울 (참/거짓)을 제안합니다. 'correct_answer'는 더 나은 이름이 될 것입니다. –

관련 문제