Using Python's not Operator: Inverting the Truth

Real Python · Intermediate ·💻 AI-Assisted Coding ·3y ago

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 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

This video teaches you how to use Python's not operator to invert the truth value of boolean expressions and objects, and how to apply it in various contexts such as conditionals, loops, and operator precedence. You will learn the basics of boolean logic, unary operations, and control flow statements in Python.

Key Takeaways
  1. Use the not operator to invert the truth value of a boolean expression
  2. Apply the not operator to numbers and collections
  3. Understand how the not operator interacts with other operations in Python
  4. Use parentheses to indicate the order of operations when mixing comparisons with boolean operators
  5. Apply the not operator in conditionals and loops
💡 The not operator always returns true or false, and can be used to negate or invert the value of a boolean expression or object.

Related AI Lessons

When AI Writes Most of My Code: What Happens to My Identity as a Software Engineer?
Explore how AI coding tools impact your identity as a software engineer and learn to adapt to the changing landscape of software development
Medium · AI
When AI Writes Most of My Code: What Happens to My Identity as a Software Engineer?
Explore how AI coding tools impact software engineer identity and adapt to the changing landscape
Medium · Programming
How AI Is Changing Software Development (2023–2026)
Learn how AI is revolutionizing software development with automated coding tools and techniques, increasing productivity and efficiency
Medium · Machine Learning
How AI Is Changing Software Development (2023–2026)
Discover how AI is transforming software development with automation, code completion, and more, and why it matters for developers' productivity and efficiency
Medium · Programming
Up next
Azure Security Priorities for 2026: Identity, Governance, AI Security & Zero Trust
Valto Microsoft Specialists
Watch →