🔍 Deep Dive: Logical Operators in Python
Logical operators in Python are used to combine conditional statements. They return Boolean values: True
or False
, based on the logic applied to the operands.
Logical Operators Overview
Operator | Description | Example | Result |
---|---|---|---|
and |
Returns True if both statements are true |
(5 > 2) and (3 < 4) |
True |
or |
Returns True if at least one statement is true |
(5 > 2) or (3 > 4) |
True |
not |
Reverses the result, returns False if the result is true |
not(5 > 2) |
False |
Examples in Python
a = 10
b = 5
c = 7
print(a > b and c < a) # True
print(a < b or c == 7) # True
print(not(a < b)) # True
Using Logical Operators in Conditionals
These operators are very useful when you want to check multiple conditions inside an if
statement:
age = 20
has_id = True
if age >= 18 and has_id:
print("Access granted!")
else:
print("Access denied.")