December 2018
Beginner to intermediate
796 pages
19h 54m
English
Assertions are a nice way to make your code ensure your assumptions are verified. If they are, all proceeds regularly but, if they are not, you get a nice exception that you can work with. Sometimes, instead of inspecting, it's quicker to drop a couple of assertions in the code just to exclude possibilities. Let's see an example:
# assertions.pymylist = [1, 2, 3] # this ideally comes from some placeassert 4 == len(mylist) # this will breakfor position in range(4): print(mylist[position])
This code simulates a situation in which mylist isn't defined by us like that, of course, but we're assuming it has four elements. So we put an assertion there, and the result is this:
$ python assertions.pyTraceback (most recent call last): File ...
Read now
Unlock full access