"""
This program leads the user through a quiz
based on a glossary of CS 21 key terms.
David Mauskop and [YOUR NAME HERE], CS 21
"""
from random import *
def readDefinitions(fileName):
"""
Purpose: Read terms and definitions in from a file
Parameters: file - the name of the glossary file
Returns: A list of lists with the terms and definitions
"""
defsFile = open(fileName, "r")
data = []
for line in defsFile:
line = line.strip()
values = line.split(":")
data.append(values)
return data
def printInstructions():
"""
Purpose: Prints instructions for the quiz.
Parameters: n/a
Returns: n/a
"""
print("\nThis program will test your CS 21 knowledge")
print("For each definition, enter the corresponding term\n")
def askQuestion(questionNo, definition):
"""
Purpose: Show a definition to the user, ask them to enter corresponding term.
Paramters: questionNo - the question number
definition - the term definition
Returns: the user's answer
"""
print("\nQuestion %d" % questionNo)
print("Definition: %s" % definition)
return raw_input("Term: ")
def createQuizSummary(correct, length, mistakes):
"""
Purpose: Create a string that contains a summary of the user's
performance on the quiz
Parameters: correct - number of questions user got correct
length - number of questions on the quiz
mistakes - a list of the terms user got wrong
Returns: the string
"""
line1 = "%d out of %d questions correct" % (correct, length)
line2 = "These are the terms you need to practice: %s" % mistakes
return "\n%s\n%s\n" % (line1, line2)
def logResult(fileName, summary):
"""
Purpose: Append a summary of the quiz to a log file
Parameters: fileName - name of the log file
summary - a string summarizing the quiz
Returns: n/a
"""
logFile = open(fileName, 'a')
logFile.write(summary)
def main():
questionFile = "glossary.txt"
logFile = "quiz-log.txt"
quizLength = 6
numCorrect = 0
mistakeList = []
questions = readDefinitions(questionFile)
printInstructions()
for i in range(quizLength):
question = choice(questions)
definition = question[0]
term = question[1]
user_answer = askQuestion(i+1, definition)
if user_answer == term:
print("That's correct!")
numCorrect += 1
else:
print("Sorry, the correct answer was %s." % term)
mistakeList.append(term)
summary = createQuizSummary(numCorrect, quizLength, mistakeList)
print(summary)
logResult(logFile, summary)
main()