Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Avoiding Unnecessary Negative Logic

00:00 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.

00:14 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.

00:38 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.

00:55 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.

01:10 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.

01:24 If you’re writing an ifelse statement and there’s nothing to do in the then part, only the else part, then you should consider using negative logic with the not operator.

01:37 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 0 condition.

01:51 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 0.

02:07 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.

02:20 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.

02:33 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.

02:55 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 not operator.

03:08 Next we’ll wrap things up.

Become a Member to join the conversation.