The not keyword is a logical operator used to reverse the Boolean value of a condition or expression. It returns True if the operand is False, and returns False if the operand is True.
a = True
print(not a)
Output
False
Explanation: The value of a is True. Applying the not keyword reverses it to False, which is printed as the output.
Syntax
The general syntax of the not keyword is shown below:
not condition
Or, it can be used inside an if statement as follows:
if not condition:
# code
Truth Table
The following truth table shows the result of the not keyword for different Boolean values.
| Condition | Result |
|---|---|
| True | False |
| False | True |
Explanation: The not keyword always returns the opposite Boolean value of the given condition.
With Boolean Expressions
The not keyword can also be used with Boolean expressions to reverse their result.
print(not False)
print(not True)
print(not (5 > 7))
print(not (10 > 5))
Output
True False True False
Explanation:
- not False returns True.
- not True returns False.
- 5 > 7 is False, so not (5 > 7) returns True.
- 10 > 5 is True, so not (10 > 5) returns False.
In Conditional Statements
The not keyword is commonly used in if statements to execute code when a condition is False.
log = False
if not log:
print("Please log in")
Output
Please log in
Explanation: The value of log is False. Therefore, not log becomes True, so the print() statement is executed.
With Different Data Types
The not keyword can also be used with different data types. In Python, empty values are considered False, while non-empty values are considered True.
print(not "Python")
print(not "")
print(not [1, 2, 3])
print(not [])
Output
False True False True
Explanation:
- A non-empty string ("Python") is truthy, so not returns False.
- An empty string ("") is falsy, so not returns True.
- A non-empty list is truthy, so not returns False.
- An empty list is falsy, so not returns True.
Checking Whether a List is Empty
The not keyword provides a simple way to check whether a list is empty.
num = []
if not num:
print("The list is empty")
else:
print("The list is not empty")
Output
The list is empty
Explanation: An empty list is treated as False in Python. Therefore, not numbers becomes True, and the first print() statement is executed.