Quiz Flashcards
(3 cards)
load(file): The function takes the file URL, e.g., questions.csv, as a string. It opens the
file and reads in the quiz questions line by line.
A quiz question is stored in this format:
question \t answer1 \t answer2 \t answer3 \t answer4 \t correctAnswer
Each line has to be split at \t to access the needed information. Then, the function add has to be called to add a quiz question to the global list of quiz questions questions.
import random
import os
os.chdir("C:/Users/sammy/Pythonprojects/data") questions = [] def loadquestions(path): global questions questions = [] text = open(path) for line in text: data = line.split("\t") addQuestion(data[0],data[1:len(data)-1],data[-1]) #question, answers, correct
loadquestions(“questions.txt”)
add(question,answers,correct): The function takes the question as a string, the four answers as a list of strings and the correct answer as an integer value in the range [1,4].
A dictionary q is initialized, which maps the question to “question”, the answers to
“answers” and the correct answer to “correct”.
Finally, q is added to the global list of
quiz questions questions.
def addQuestion(question, answers, correct): q = {} q["question"] = question q["answers"] = answers q["correct"] = int(correct) questions.append(q)
play(n): The function to be called to run the quiz with n questions. It retrieves a list
of n random questions by calling getRandomQuestions and initializes a variable score to count the number of correct answers.
Each question is printed on the screen us-
ing the printQuestion function, and the user input is checked for correctness. score
is incremented if the answer is correct.
After the user has answered all questions, the printMessage function is called that prints the result on the screen.
def printQuestion(q): print(q["question"]) for i in range(len(q["answers"])): print(str(i+1)+": "+q["answers"][i])
def getRandomQuestions(n): return random.sample(questions,n)