Logical Operators
Logical operators (and
, or
, not
) are used to combine or invert boolean values (True
and False
). They are essential for creating complex conditional logic that controls the flow of your programs.
The Core Logical Operators
and
The and
operator returns True
only if both of its operands are true.
A | B | A and B |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Pyground
Check if a user is both an admin and is active.
Expected Output:
Can access dashboard? True What if the user is not active? False
Output:
Truthiness: Beyond True
and False
In Python, logical operators can work with any value, not just booleans. Every value in Python has an inherent “truthiness.”
- Falsy Values: These values are treated as
False
in a boolean context.None
False
0
(of any numeric type, e.g.,0
,0.0
,0j
)- Empty sequences and collections:
''
,[]
,()
,{}
,set()
- Truthy Values: All other values are treated as
True
.
Pyground
Demonstrate truthiness with an empty list and a non-empty string.
Expected Output:
The list is empty, so it is 'falsy'. The string 'Alice' is not empty, so it is 'truthy'.
Output:
Short-Circuit Evaluation
This is a crucial and powerful feature of the and
and or
operators. Python evaluates them from left to right and stops as soon as the result is determined.
A and B
: IfA
is falsy, the whole expression must be false, so Python returnsA
and never evaluatesB
. IfA
is truthy, Python must evaluateB
and returnsB
.A or B
: IfA
is truthy, the whole expression must be true, so Python returnsA
and never evaluatesB
. IfA
is falsy, Python must evaluateB
and returnsB
.
Use Case 1: Guarding Against Errors
Short-circuiting is often used to prevent errors, like trying to divide by zero.
Pyground
Safely calculate a ratio only if the denominator is not zero.
Expected Output:
Result with denominator 0: 0 Result with denominator 20: 5.0
Output:
Use Case 2: Providing Default Values
The short-circuit behavior of or
provides a concise way to select a default value.
Pyground
A user can provide a username, but if they leave it empty, default to 'Guest'.
Expected Output:
Username: Guest Username: Riya
Output:
Combining with Comparison Operators
The most common use of logical operators is to build complex conditions by combining the results of comparison operators.
Pyground
Determine if a student is on the honor roll. They must have a GPA of 3.5 or higher AND not be on academic probation.
Expected Output:
GPA: 3.7, On Probation: False Eligible for Honor Roll? True