Using Python's not Operator: Inverting the Truth
Key Takeaways
The video demonstrates the use of Python's not operator for negating boolean expressions and objects, and its application in various contexts such as conditionals, loops, and operator precedence. It covers the basics of boolean logic, unary operations, and control flow statements in Python.
Full Transcript
hello and welcome to this course on using the python not operator if you're familiar with conditionals for things like if statements and while loops and you want to express some of your conditions in a much clearer manner then you should enjoy this course in this course we'll look at the basics of the not operator show how it can be used in conditionals and other contexts then learn the best practices for using it in python not is one of the three boolean operators implemented in python the other two are called or and and boolean expressions are used in conditionals to control the flow of the instructions in a python program this course is specifically about the not operator and it's based on a similar tutorial by leodonis pozo ramos you can find more tutorials and courses on boolean operators here at realpython after completing this course you will know how the python not operator works how to use the not operator in both boolean and non-boolean contexts and when to use it and when not to use it in your python programs let me tell you about the tools i'll be using in this course for python program files i use visual studio code with the dark plus theme my terminal shell is iterm 2 for mac os and for my repl i use pt python with its native theme i'm howard francis and i'm excited to lead you through this course on the python not operator let's get started in this lesson you'll learn the basics of boolean operations and a bit how python implements them boolean logic is named after george boole who developed a whole system of mathematics based on two values called true and false and the operations on them and or and not since computers work in binary two values although we call them one and zero william algebra became the natural way to design and build computers boolean expressions are the types of expressions we use in if and while statements the use of boolean operators can allow you more precise and sometimes more complicated conditions to describe which branch of an if statement to execute or when to repeat an iteration in a while loop here's some terminology relevant to boolean logic in python boolean is a type of value that can be either true or false we signify that using the keyword bool for that type and is the subtype of the int integer type there are two boolean values true or false and in python those are capitalized internally python stores true as one and false as zero a boolean expression is an expression that returns either true or false it does a computation and returns true if the result of that computation is true and false if that computation was false the three boolean operators are and which connects two expressions or which also connects two expressions and not which only acts on a single expression in python the keywords that we use for these boolean operators are in fact and or and not in the next lesson you'll start seeing the not operator in use let's take a look at how the not operator works in python python uses not to implement the negation operation negation is a unary operation meaning it takes just one expression as an operand in python that operand could be a boolean expression or another type of python object if the operand it's applied to evaluates to true then the result of the not operation is false similarly if the operand evaluates to false then the result of the not operation applied to it is true many times the function of boolean operators is described in a truth table here is the one for naught it basically says that if the operand is true then not operand is false and if the operand is false then the not of it is true where might you use the not operator one case is when you're looking for a condition that isn't met during some if or while statement negating or inverting the value of a boolean expression checking to see if an item is not in a given collection of things and sometimes in checking for object identity and this course will show you examples of all of these first will be examples of negation let's do some negation in its simplest use not inverse the truth value of a boolean expression so if you create two variables and then perform a comparison on them you can see that x is not bigger than y but if you put not in front of the comparison the result of the entire expression including the not becomes true and that's the basics of what inverting a boolean expression means however every expression in python is given a truth value so you can apply not to other things as well most in fact are true but there are some that are considered false none is false and of course false is false any numeric expression with a value of zero is considered false any empty collection is also false additionally if a class has implemented a dunder method like wool or len if will returns false for that object it's considered false or if the length returns zero then that object is considered false as well so let's take a look at some examples of those 0 is considered false so not 0 should be true conversely a number like 42 is true so not 42 should be false and that doesn't change if you decide to use floating point values or even complex numbers let's take a look at some examples involving collections an empty string is considered false so its negation should be true on the other hand a non-empty string is true so its invert should be false the negation of an empty list is true while the negation of a non-empty list is false likewise the negation of an empty dictionary is true and the negation of a non-empty dictionary is false next you'll see how not can interact with other operations in python it's very likely you'll use not in conjunction with other operations in this lesson you'll learn how that works in python python uses something called operator precedence sometimes referred to as order of operations to determine which operation to perform first in an expression with multiple operators specifically boolean operators have a lower precedence than comparison operators that means comparisons will be done first before things like not and and or so for an example in an expression like not true is equal to false the comparison will be done first true does not equal false so the comparison is false but then the not is applied and not false becomes true here's another now this expression probably makes sense to you false is not true so you'd expect this to be true but this actually gives an error which you can see at the bottom of the screen what's happening python is trying to do the is equal to comparison first but the first thing it sees on the right is the word not it can't apply not to true yet because it has to do the is equal to first it's like the word true isn't even there false is equal to not since python can't make sense of this expression it produces a syntax error since you want to do the not true part first you need to use parentheses just like you would a mathematical expression to indicate that operation should be performed first this way gives the intended result why is this important to know because many times you'll want to connect comparisons with boolean operators and you need to understand how python will evaluate them also note when mixed with other boolean operators not has the highest presence followed by and and then or another thing to keep in mind the result of the not operation is always true or false you saw that in the last lesson no matter what type of operand not was applied to the result was either true or false but if you're familiar with the other boolean operators perhaps you know that's not always the case with and and or it is true that often the result of and or or is true or false as these examples show but python uses something called short circuit evaluation and the way it does this means the result of an and or or operation could be one of the operands so in an expression like 0 and 42 python will note that the first operand is false and provide that as the result but if you use or instead python again noticing that 0 is false that means for or the result is whatever the second operand is in this case 42. so even though the results for and and or can be any number of things that is not the case for not not always gives a result of either true or false for more detailed look on and and or and short circuit evaluation see the real python tutorials and courses on these operators now you're ready to see places where the not operator can be used in the next few lessons you'll start to see places where the not operator is commonly used beginning with boolean contexts normally the instructions in your program progress one after the other but sometimes you want to change that there are times a certain piece of code should only be executed if some condition is true and other sections of code that should be repeated statements which cause this to happen are called control flow statements because they control the flow the order that other statements are executed to make these determinations they use a boolean condition which is evaluated to true or false so these are considered the boolean contexts were not operator might be used the first are if statements these allow a certain section of code to be executed based on some boolean condition being true or false the others are while loops these allow for certain sections of code to be repeated provided some boolean condition remains true first you'll examine the if statement
Original Description
Python’s not operator allows you to invert the truth value of Boolean expressions and objects. You can use this operator in Boolean contexts, such as if statements and while loops. It also works in non-Boolean contexts, which allows you to invert the truth value of your variables.
Using the not operator effectively will help you write accurate negative Boolean expressions to control the flow of execution in your programs.
This is a portion of the complete course, which you can find here:
https://realpython.com/courses/using-not-operator/
The rest of the course covers:
- Using not in if statements
- Using not in Boolean while loops
- Using not in non-Boolean contexts
- How to test for membership
- Avoiding unnecessary Negative logic
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: AI Pair Programming
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
When AI Writes Most of My Code: What Happens to My Identity as a Software Engineer?
Medium · AI
When AI Writes Most of My Code: What Happens to My Identity as a Software Engineer?
Medium · Programming
How AI Is Changing Software Development (2023–2026)
Medium · Machine Learning
How AI Is Changing Software Development (2023–2026)
Medium · Programming
🎓
Tutor Explanation
DeepCamp AI