Avoiding Unnecessary Negative Logic
The use of
not in Python programs often creates negative logic. Negative logic can be useful, but it can be overused. In this lesson, you’ll learn when to use it and when not to use it.
Negative logic reverses the meaning of some condition. This is often accomplished using the
not operator, and negative logic itself isn’t inherently bad.
00:24 You’ve seen many good examples of negative logic all throughout this course. Here’s another one: you’re trying to work with a file, but if it doesn’t exist, it should be initialized first.
So you have a condition,
if not file.exists(), which expresses the condition properly. If the file doesn’t exist, it needs to be created. This is a good use of negative logic.
What would it look like using positive logic? It might look something like this. The test would be
if the file exists, but what do you do at this step if the file exists? Nothing.
You need to create the file if it doesn’t exist, but if this condition is true, there’s nothing that needs to be done. So you use
pass to indicate an empty block, but this isn’t very Pythonic code.
If you’re writing an
else statement and there’s nothing to do in the then part, only the
else part, then you should consider using negative logic with the
But that doesn’t mean negative logic is always good. Let’s look at a custom absolute value program that some programmer may have written. The programmer wants to focus on the less than
This first version uses negative logic. See the word
not in front of the inequality? So checking
< 0, then negating that. So it’s really asking if the number is bigger than or equal to
That really just makes things confusing. Here’s a better version using positive logic, but still using the
< 0 comparison. This version uses positive logic.
It does have to switch the then part with the implied
else part from the previous version, but it still keeps the programmer’s desire to use the
< 0 inequality.
Here’s another example of unnecessary negative logic with an inequality check. The programmer uses
not along with the
== (is equal to) operator, but Python has an
!= (is not equal to) operator, and it would be much better to use that in this situation.
So again, use negative logic when it’s appropriate, but when a simpler condition or branch can be written with positive logic, try to avoid using the
Become a Member to join the conversation.