Ich habe Probleme mit meinem Code, ich weiß nicht, wie man eine Stichprobe der Fragen bekommen. Dies ist der Code und es gibt mir einen Key Error. Ich versuche, eine zufällige Frage aus der Liste der Fragen zu drucken, aber es sagt mir, dass Fragen ein Wörterbuch ist. Kann mir jemand helfen?? HierRandom Quiz Generator
ist der Code
#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()
dies ist ein Beispiel für meine Daten in einer CSV-Datei:
Wer die World Series gewann in diesem Jahr, die Cubs, Mets, Kardinäle? , Die Indianer
Wie viele Spieler Verteidigung auf dem Feld spielen?, Neun, Sechs, zehn, zwanzig
Wie viele Innings in einem Baseball-Spiel ist? Nine, Ten, Seven, Six
Sie rufen 'ask_questions' mit' questions' und ' Schlüssel, aber es scheint eine Frage und die Antworten als Arrgumente zu erwarten. –