import cgitb; cgitb.enable() from web_form import * from html_util import * def score_question(form_data, htmldoc, qnum, correct_answer): """ Looks for an answer for question number qnum in form_data and compares it to the correct_answer. Outputs an HTML message telling the user if their answer was correct or not. Returns True if the user's answer matches the correct answer exactly. qnum: int > 0 htmldoc: HTMLDocument to output to correct_answer: string """ correct = False id = "q%d" % qnum htmldoc.new_paragraph() htmldoc.write_text("Question %d: " % qnum, bold=True) htmldoc.newline() htmldoc.write_text("Correct answer: ") htmldoc.write_text(correct_answer, bold=True) htmldoc.newline() if id in form_data: # if user answered question ans = form_data[id] else: ans = None if ans: htmldoc.write_text("Your answer: ") htmldoc.write_text(ans, bold=True) htmldoc.newline() if ans.strip() == correct_answer: htmldoc.write_text("Correct!", color="green", bold=True) correct = True else: htmldoc.write_text("Wrong!", color="red", bold=True) else: htmldoc.write_text("You did not provide an answer.") return correct # create a helper to generate the HTML doc = HTMLDocument("6.095 'IQ' test: Your Score") doc.new_section("IQ Test: Your Score") # get the values submitted by the user d = get_submitted_form_data() score = 0 # # question 1 # if score_question(d, doc, 1, "36"): score += 25 # # question 2 # if score_question(d, doc, 2, "34"): score += 25 # # question 3 # if score_question(d, doc, 3, "17"): score += 25 # # question 4 # if score_question(d, doc, 4, "sparrow"): score += 25 # # total # doc.new_paragraph() doc.write_text("Total score: ") doc.write_text(str(score), bold = True) # output the HTML doc.print_html()