-1
我遇到了我的代碼問題,我不知道如何獲得問題的隨機樣本。這是代碼,它不斷給我一個關鍵錯誤。我試圖從問題列表中打印一個隨機問題,但它告訴我問題是一本字典。誰能幫我??隨機測驗生成器
下面是代碼
#import matplotlib.pyplot as plt
import random, math, csv
def read_database(filename):
dictionary = {}
infile = open(filename, 'r')
for line in infile:
line = line.strip()
q,a1,a2,a3,a4 = line.split(',')
question = (q)
answers = [a1,a2,a3,a4]
dictionary[question] = answers
infile.close()
return dictionary
def read_results(outfile, score):
player = {}
outfile = open(outfile, "w")
name = input("What is your name?")
player[name] = score
print(score, file = outfile)
outfile.close()
def ask_question(question, answers):
score = 0
print(question[0])
for multi in answers[1:5]:
print(multi)
answer = input("Please select an answer: ")
print()
if answer == answer[0]:
print("Correct!")
score += 1
else:
print("Incorrect! - the correct answer was {0}.".format(answer[0]))
print()
return score
def main():
questions = read_database("data.csv")
score = 0
score = int(score)
print()
print()
print("=============================")
print("Welcome to the baseball quiz!")
print("=============================")
print()
print()
name = input("What is your name?")
number = int(input("Hi," + name + " there are {0} questions - how many do you want in your quiz: ".format(len(questions))))
if number > len(questions):
print("The quiz only has 10 questions, you will be asked 10 questions. ")
else:
print("You will be asked", number, "quesitons")
key_list = random.sample(questions.keys(), number)
#print(key_list)
score = 0
for key in key_list:
print(key, questions.get(key))
score = ask_question(questions, key)
print(score)
print("Your final score was {0} out of {1}.".format(score,number), score/100)
if __name__ == "__main__":
main()
這是我的數據在CSV文件的示例:
誰贏得了世界系列賽今年,小熊,大都會,主教? ,印度人
有多少球員場防守?,九,六,十,二十
多少局都在棒球比賽呢? ,九,十,七,六
要調用'和'questions'和'ask_questions'關鍵「,但它似乎期待一個問題和答案作爲參數。 –