Logical Operators in Python
What are Logical Operators? Logical operators in Python are used to combine conditional statements (expressions that evaluate to either True or False).
They are mostly used inside decision-making statements (if, while, etc.).
Syntax
# Using logical operators condition1 and condition2 condition1 or condition2 not condition
Python provides three logical operators:
- and: Returns True if both conditions are true.
- or: Returns True if at least one condition is true.
- not: Returns the opposite (negation) of the condition.
Example: and Operator.
Python
x = 10 y = 20 # Both conditions must be true if x > 5 and y > 15: print("Both conditions are True") else: print("At least one condition is False")
Output Both conditions are True.
Example: or Operator.
Python
a = 5 b = 8 # Only one condition needs to be true if a > 10 or b > 5: print("At least one condition is True") else: print("Both conditions are False")
Output At least one condition is True
Example: not Operator.
Python
is_logged_in = False # not reverses the result if not is_logged_in: print("User is not logged in") else: print("User is logged in")
Output User is not logged in