How to Use Not Operator in Python: Simple Guide
In Python, the
not operator is used to reverse the value of a boolean expression. It returns True if the expression is False, and False if the expression is True.Syntax
The not operator is a unary operator that takes one boolean expression and reverses its value.
- not expression: Returns
TrueifexpressionisFalse, otherwise returnsFalse.
python
result = not expressionExample
This example shows how not reverses the boolean value of a variable and a condition.
python
is_raining = False print(not is_raining) # True number = 10 print(not (number > 5)) # False empty_list = [] print(not empty_list) # True because empty list is False in boolean context
Output
True
False
True
Common Pitfalls
One common mistake is forgetting that not has higher precedence than and and or operators, so use parentheses to avoid confusion.
Also, not works on boolean context, so non-boolean values are converted to True or False before applying not.
python
a = True and False # Evaluates as (True and False) = False b = not True and False # Evaluates as (not True) and False = False and False = False c = not (True and False) # Evaluates as not (False) = True print(a) # False print(b) # False print(c) # True
Output
False
False
True
Quick Reference
| Operator | Description | Example | Result |
|---|---|---|---|
| not | Reverses boolean value | not True | False |
| not | Reverses boolean value | not False | True |
| not | Used with expressions | not (5 > 3) | False |
| not | Works on truthy/falsy values | not [] | True |
Key Takeaways
The not operator reverses the truth value of an expression in Python.
Use parentheses to clarify expressions when combining not with other operators.
Not works on boolean context, so non-boolean values are converted first.
It is useful for negating conditions in if statements and loops.
Remember that not has higher precedence than and, or operators.