The not
keyword in Python is a logical operator used to negate a Boolean value or expression. If the expression evaluates to True, not converts it to False, and vice versa. It is often used to reverse conditions in decision-making statements like if.
Example
is_raining = False
if not is_raining:
print("It's not raining. You can go outside!")
Output:
It's not raining. You can go outside!
Syntax
not expression
expression
: Any Boolean expression or value that can evaluate to True or False.
Why Use not?
- Negate Boolean Values: Reverse the result of a condition or Boolean value.
- Simplify Logic: Make conditions more readable by expressing “not something.”
- Control Flow: Helps define alternative conditions in decision-making constructs.
Common Examples
1. Negating a Boolean Value
is_logged_in = False
if not is_logged_in:
print("You need to log in!")
Output:
You need to log in!
2. Negating an Expression
x = 5
if not x > 10:
print("x is not greater than 10")
Output:
x is not greater than 10
3. Using not in Function Calls
def is_even(number):
return number % 2 == 0
if not is_even(5):
print("The number is odd")
Output:
The number is odd
4. Combining not with Logical Operators
age = 16
has_permission = False
if not (age >= 18 or has_permission):
print("Access denied")
Output:
Access denied
5. Using not with Lists
shopping_list = []
if not shopping_list:
print("The shopping list is empty")
Output:
The shopping list is empty