Assert Statements#
You may have noticed that MUDE uses assert statements for some of the automatic grading of the PAs. Knowing how these assert statements work can be very useful for you in troubleshooting your submissions if they don’t pass the first time around.
Assert statements are like small little “fact-checkers” that you can insert into your code. An assert statement answers a true/false question; it will will cause an error if false and do nothing if true.
For example, if a matrix should be 4x6 you can use an assert statement to check this; if the matrix is not the right size, and error will occur.The reason it is useful is that it causes your code to break for a very specific reason, so that you can identify problems and fix them efficiently and confidently. Sounds useful, right?! Luckily assert statements are also quite simple:
There are two cases of this statement that we will use:
Case 1:
assert <logical_argument>
Case 2:
assert <logical_argument>, 'my error message'
Task 1:
Execute the cell below and observe the error. Note that it very specifically is an AssertionError.
See if you can fix the assert statement itself to prevent the error from occurring.
x = 9
assert x == 1
Task 2:
Now try fixing the cell below by 1) adding your own error message (see Case 2 above), and 2) forcing the assert statement to fail. Confirm that you can see error message in the error report. Ensure that your error message happens in cell 2
y = 0
assert y != 1, YOUR_MESSAGE_HERE
By Robert Lanzafame, Delft University of Technology. CC BY 4.0, more info on the Credits page of Workbook.