2016-11-21 170 views
-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文件的示例:

谁赢得了世界系列赛今年,小熊,大都会,主教? ,印度人

有多少球员场防守?,九,六,十,二十

多少局都在棒球比赛呢? ,九,十,七,六

+0

要调用'和'questions'和'ask_questions'关键“,但它似乎期待一个问题和答案作为参数。 –

回答

0

功能ask_question(question, answers)需要获得问题和可能的答案列表作为参数。

因此你需要调用它像这样

score = ask_question(key, questions.get(key)) 

在这种情况下key是问题和可能的答案列表questions.get(key)