Exercise checking using check-answer button#
Using the python-enabled interactivity, exercise checking can be intuitively incorporated using a widgets which checks the value of certain variables with respect to the answer. These examples show different approaches to achieving this goal.
A function has been made to check the value of a variable. As input values it takes the variable name, the expected value (correct answer) and how these values should be compared. You need to add this function to each page, including the imports, and add the thebe-remove-input-init
tag to the cell.
import ipywidgets as widgets
from IPython.display import display
import operator
def check_answer(variable_name, expected, comparison = operator.eq):
output = widgets.Output()
button = widgets.Button(description="Check answer")
def _inner_check(button):
with output:
if comparison(globals()[variable_name], expected):
output.outputs = [{'name': 'stdout', 'text': 'Correct!', 'output_type': 'stream'}]
else:
output.outputs = [{'name': 'stdout', 'text': 'Incorrect!', 'output_type': 'stream'}]
button.on_click(_inner_check)
display(button, output)
To check a float value, you could use math.isclose
as a function. For checking the equivalence of arrays, you might consider numpy.array_equiv
You can choose to include the correct answers in the same notebook. If students download the page and you didn’t specify a custom url, they can find the correct answers. You can also place the correct answers in a seperate .py file which you import in the notebook.
Example#
import ipywidgets as widgets
from IPython.display import display
import operator
def check_answer(variable_name, expected, comparison = operator.eq):
output = widgets.Output()
button = widgets.Button(description="Check answer")
def _inner_check(button):
with output:
if comparison(globals()[variable_name], expected):
output.outputs = [{'name': 'stdout', 'text': 'Correct!', 'output_type': 'stream'}]
else:
output.outputs = [{'name': 'stdout', 'text': 'Incorrect!', 'output_type': 'stream'}]
button.on_click(_inner_check)
display(button, output)
# This example has the user type in the answer as a Python variable, but they need to run the cell to update the answer checked!
pi = 3.14
import math
check_answer("pi", 3.14, math.isclose)