Python读取错误

2024-04-24 23:36:06 发布

您现在位置: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")

如果你能指出为什么它不能正常工作,那就太棒了=)


Tags: theanswertitledeflineblockfilenext
1条回答
网友
1楼 · 发布于 2024-04-24 23:36:06

此代码:

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")

如果答案是正确的,我想你也要显示分数,所以把最后一行缩进。你知道吗

相关问题 更多 >