首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用文本文件的测验程序

使用文本文件的测验程序
EN

Stack Overflow用户
提问于 2015-03-01 13:03:49
回答 2查看 8.7K关注 0票数 0

我试图用Python创建一个测验程序,其中问题存储在一个txt文件中,答案存储在另一个文件中。问题在文本文件中如下所示:

Which one of these is a percussion instrument? A. Trumpet B. Euphonium C. Viola D. Glockenspiel

该程序以随机顺序拉出问题,并保持正确答案数量的分数。但是,由于涉及到多行代码,并且需要从另一个文件中获取答案,我不知道从哪里开始。如果你能给我提供任何帮助,我将不胜感激。如果您需要澄清任何事情,请随时提问。

编辑:好的,我决定稍微改变一下我的想法,这可能会让它变得更容易。使用CSV文件可能是更好的选择。这是我到目前为止所拥有的。

代码语言:javascript
运行
复制
def Trivia():
score=0
myFile = open("farming.csv","r") # opens the CSV file and stores it in the array myFile
players = myFile.readlines() # reads the lines of the CSV file into the variable players
questionno=1
while questionno < 6:

    for p in players:
        data = p.split(",") #splits each cell of the CSV file into its parts
    questions = data[0]
    answera = data[1]
    answerb = data[2]
    answerc = data[3]
    CorrectAnswer = data[4]
    print("Question #",questionno)
    print(questions) #prints the question and the 3 answers
    time.sleep(0.5)
    print(answera)
    time.sleep(0.5)
    print(answerb)
    time.sleep(0.5)
    print(answerc)
    time.sleep(0.5)
    answer = input("Answer? ") #asks the user for their answer
    time.sleep(1)
    print(".")
    time.sleep(1)
    print(".")
    time.sleep(1)
    print(".")

    if answer == CorrectAnswer: #checks if the answer is correct and prints approptiate responses
        print("That is the correct answer")
        score=score+1
        time.sleep(1)
    else:
        print("That is not the correct answer")
        time.sleep(1)
    print("Your current score is", score)
    print("")
    questionno = questionno+1

myFile.close()

我现在的问题是,我不知道如何进入测验中的下一个问题。使用这种格式,它会一直问同样的问题。有什么想法吗?

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2015-03-01 13:11:51

这个问题有两个方面:保存什么和如何保存。让我们先回答“如何”。

看起来您需要的是serialization,这是一种奇特的方式,意思是“以特定格式保存数据”。我会学习picklejson。这将允许您保存和加载对象,例如,您可以保存表示问题的类。

关于你保存了什么,而不是如何保存,我想每个答案都应该和一些问题一起保存,然后你就可以在它们之间建立链接-有点像foreign keys in a DB

祝好运!

票数 0
EN

Stack Overflow用户

发布于 2017-11-19 01:24:41

到目前为止,我还不能百分之百确定我还没有亲自运行程序进行检查。但我认为可能是"While“模块。它说,当questionno小于6时,做这个问题,所以当你将1加到questionno时,它仍然小于6,再次运行程序。把它也改成这个

如果问题If == 1:.......

对于测验中的下一个问题,您只需以

如果问题If == 2:.......

现在写第二个测验

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28790297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档