assert statement asserts that a value is
True. If the value is not
AssertionError is raised.
Consider the following code.
The first line basically does nothing because the argument to
True. The second line will throw an
The assert statement is useful for explaining code. Let’s say I wrote a piece of code to explain how to add numbers in Python.
sum = 2 + 2
assert sum == 4
assert line asserts that the variable
sum must equal 4 – otherwise the code wouldn’t work. Without assert, the above code would have to be written like this.
sum = 2 + 2
# sum now equals 4
assert statement makes it a little more eloquent to write about code.
Today I helped a colleague solve an issue she was having simply by listening. By giving her an opportunity to discuss the topic with me, she was able to work out the solution herself. Before I had even fully understood the problem, she thanked me for the help.
This technique of problem solving even has a name: “Rubber Duck Debugging“. The term comes from a story in the book The Pragmatic Programmer.
The idea is to obtain a rubber ducky, keep it at your desk, and explain your code
to it whenever you are stuck on a problem – though you can use a human in place of the duck, if you prefer. The human doesn’t need to programmer. The technique is based on the idea that teaching a subject forces an evaluation from a different perspective allowing for a deeper insight into the problem.