In interactive notebooks it can be useful to ask students to respond to a multiple choice questions. This notebook demonstrates how this can be done, either using local code or by embedding an external site.
Setting up an MCQ can be done using a small function which calls the MCQ class, providing the question as a string and the options and whether the answer is correct as a list of dictionary objects. You can also provide feedback if the answer is correct or incorrect (or both) using the feedbackCorrent and feedbackIncorrect keys. By default only ticked answers will be marked, unless the optional argument check_selected_only is set to False. An example MCQ is provided in the file mcq.py:
def mcq_1(): question = "<p><strong>Select the correct answers about the Python Language (more than one answer may be correct)</strong><p>" options_dict = [ { "text": "Python is the fastest coding language", "correct": False, "feedbackIncorrect": "Python is not the fastest — precompiled languages like C or Rust are generally faster.", }, { "text": "Python is a great language to start with", "correct": True, "feedbackCorrect": "Yes! Python's simple syntax makes it a great first language.", }, { "text": "Python was developed in the 1980s", "correct": True, "feedbackCorrect": "Correct — Python was conceived in the late 1980s by Guido van Rossum.", }, ] quiz = MCQ(question, options_dict) return quiz.quiz()
from mcq import mcq_1
mcq_1()If you want to use code as part of the question format it carefully using a “”" syntax and <pre> and <code> tags, as in the example below.
question = """ <p>Analyse the following code and select the two correct answers <pre> <code> for i in range(10): if i % 2 == 1: print(f"{i} is odd") else: print(f"{i} is even") </code></pre></p> """
from mcq import mcq_2
mcq_2()It may not be obvious to students that they have all the correct answers unless you tell them at the start how many are correct.
Alternative Embed Approach¶
It is also possible to host the code to create MCQs on CodePen and embed the question in your notebook. To do this, use this example as a template and click Fork in the bottom right (you may need to create a free account). This should create a new copy of the problem for you to edit:
In the HTML box you can edit the question
In the JS box, edit the const quizData to reflect the answer options you want.
In the JS box, edit the const CHECK_SELECTED_ONLY to false if you want to change the feedback behaviour
Save your codepen
From the bottom right click Embed - a new dialogue opens
In the top pane make sure only result is selected
Click iframe in the lower right tab and copy the src from the displayed code to use in your notebook
from IPython.display import IFrame
IFrame(
src="https://codepen.io/StuartLW/embed/WbbNvXe?default-tab=result",
width=1500,
height=400,
)