One “gotcha” that stumped me a few times when I started out programming in python was around the use of boolean operators, especially the “and” operator.
A typical use case of “and” is the following:
An example that’s a little bit more complicated is something like this:
The output is as expected:
>> I can purchase apples
>> I can’t purchase donuts
But if we later write unit tests for the function, we get an error.
>> AssertionError: 8 != True
The “gotcha” here is that function can_purchase is not returning a boolean.
If you read the python documentation on Boolean Operations carefully, you’ll see the following table.
||if x is false, then y, else x||(1)|
||if x is false, then x, else y||(2)|
||if x is false, then
You’re guaranteed a boolean when you use the “not” operator, but not when using “or” or “not”.
This was a little bit more obvious for the “or” operator as it’s widely used for setting a default value when looking up elements in a dictionary.
The easiest solution is to properly return a boolean,
but people may simply forget to do so. Boolean operators can also be chained, making the problem less obvious at first.
Do you remember any fun “gotchas” from when you started programming in python?