In Python, Logical Operators are used to combine conditional statements. They allow you to perform complex checks by evaluating multiple expressions at once. Like comparison operators, logical operators always return a Boolean value (True or False).
They are the "connectives" of programming logic, essential for creating sophisticated decision-making structures in your code.
There are three main logical operators in Python: and, or, and not.
| Operator | Description | Logic |
| and | Returns True if both statements are true. | True and True $\rightarrow$ True |
| or | Returns True if at least one statement is true. | True or False $\rightarrow$ True |
| not | Reverses the result (True becomes False, and vice-versa). | not(True) $\rightarrow$ False |
| A | B | A and B | A or B | not A |
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
Python uses Short-Circuit Evaluation to optimize performance:
and Short-circuit: If the first expression is False, Python doesn't check the second one because the result is already guaranteed to be False.
or Short-circuit: If the first expression is True, Python doesn't check the second one because the result is already guaranteed to be True.
This is useful for preventing errors, such as checking if a number is not zero before dividing by it:
if count != 0 and (total / count) > 10:
# Sample Variables has_license = True age = 20 has_car = False # Using 'and' # Both conditions must be True can_drive = age >= 18 and has_license print(f"Can drive? {can_drive}") # Output: True # Using 'or' # Only one condition needs to be True needs_transport = has_car == False or age < 18 print(f"Needs transport help? {needs_transport}") # Output: True # Using 'not' # Flips the boolean value is_weekend = False print(f"Is it a working day? {not is_weekend}") # Output: True # Combining multiple operators # Logic: (True and True) or False -> True or False -> True result = (age > 18 and has_license) or has_car print(f"Complex Check: {result}")
In Python, logical operators don't just work with True and False. They can work with any object. Python evaluates "empty" objects (like 0, "", [], None) as Falsy and almost everything else as Truthy.
x and y: Returns x if x is Falsy; otherwise, returns y.
x or y: Returns x if x is Truthy; otherwise, returns y.
print(0 or "Python") # Output: Python (because 0 is Falsy) print("Hello" and 100) # Output: 100 (because "Hello" is Truthy)
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION