2017-05-04 145 views
-2

這個Python代碼選擇了錯誤的信息作爲答案,它選擇了正確答案的第一個字母而不是相應的數字。Python讀取不正確

#Trivia Challenge Game 
#Trivia game that reads a plain text file 

import sys 

title = "Title" 

def open_file(file_name, mode): 
    try: 
     the_file = open(file_name,mode) 
    except IOError as e: 
     print("Unable to open the file",file_name,"ending program \n",e) 
     input("\n\n press the enter key to exit") 
     sys.exit() 
    else: 
     return the_file 

def next_line(the_file): 
    """returns 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 i 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 the quiz") 
    print("\t\t",title,"\t\t") 

def main(): 
    trivia_file = open_file("data.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 i in range(4): 
      print("\t",i+1,"-",answers[i]) 

     #get answer 
     answer = input("whats your answer:") 
     #check answer 
     print(correct," ",answer) 
     if answer == correct: 
      print("Right!",end=" ") 
      score += 1 
     else: 
      print("Wrong!",end =" ") 
      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() 
input("press the enter key to exit") 

如果你能指出它爲什麼不正確,這將是真棒工作=)

+0

預期產量是多少?數據文件的內容是什麼? – Kewl

回答

0

此代碼:

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

獲取文件的下一行,替換「/」與「\ n」,然後獲取結果字符串的第一個字符。不知道在數據文件中正確答案的格式,我只能猜測你想擺脫這種東西,但如果正確答案的數量是在一個單獨的線,你應該這樣做:

correct.splitlines() 

然後選擇結果列表的適當索引。

而且,在這裏:

if answer == correct: 
     print("Right!",end=" ") 
     score += 1 
    else: 
     print("Wrong!",end =" ") 
     print(explanation) 
     print("score: ",score,"\n\n") 

我想你想顯示的比分也如果答案是正確的,那麼去縮進,最後一行。