【发布时间】:2019-04-30 12:21:59
【问题描述】:
我的任务是使用 python 进行测验,问题存储在外部文件中。但是,我不知道如何让我的问题随机化,并且一次只显示 20 个可能的问题中的 10 个
我尝试过使用 import random 但语法 random.shuffle(question) 似乎无效。我不知道现在该怎么办。
question.txt 文件的布局如下:
Category
Question
Answer
Answer
Answer
Answer
Correct Answer
Explanation
我的代码:
#allows program to know how file should be read
def open_file(file_name, mode):
"""Open a file."""
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\nPress the enter key to exit.")
sys.exit()
else:
return the_file
def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line
#defines block of data
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)
time.sleep(1.5)
#beginning of quiz questions
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 i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer
answer = input("What's your answer?: ")
# check answer
if answer == correct:
print("\nCorrect!", end=" ")
score += 1
else:
print("\nWrong.", 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()
这是与程序相关的大部分代码。我将非常感谢任何可用的支持。
【问题讨论】:
-
您需要在文件中一次性读入所有问题及其答案,然后可能随机播放问题(及其答案),最后询问每个问题反过来。 (另见:stackoverflow.com/questions/976882/shuffling-a-list-of-objects)
标签: python python-3.x random