Boolean Expressions
Constructing Complex Logical Conditions
Boolean expressions are combinations of values, variables, and operators that evaluate to either True
or False
. They form the backbone of decision-making in Python programming.
Basic Boolean Expression Patterns
## Simple boolean expressions
x = 10
y = 5
## Comparison expressions
print(x > y) ## True
print(x < y) ## False
print(x == y) ## False
print(x != y) ## True
Combining Logical Operators
AND Operator
def is_adult_student(age, is_enrolled):
return age >= 18 and is_enrolled
## LabEx Example
print(is_adult_student(20, True)) ## True
print(is_adult_student(16, True)) ## False
OR Operator
def has_discount(is_student, is_senior):
return is_student or is_senior
print(has_discount(True, False)) ## True
print(has_discount(False, True)) ## True
print(has_discount(False, False)) ## False
Complex Boolean Expressions
def check_access(age, has_permission, is_admin):
return (age >= 21 and has_permission) or is_admin
## Nested logical conditions
print(check_access(22, True, False)) ## True
print(check_access(20, True, True)) ## True
print(check_access(19, False, False)) ## False
Boolean Expression Evaluation Flow
graph TD
A[Start Boolean Expression] --> B{Evaluate Left Side}
B --> |True| C{Evaluate Operator}
B --> |False| D[Short-Circuit Evaluation]
C --> |AND| E{Evaluate Right Side}
C --> |OR| F[Return Result]
E --> |True| G[Return True]
E --> |False| H[Return False]
Short-Circuit Evaluation
Python uses short-circuit evaluation to optimize boolean expressions:
def risky_operation(x):
print("Operation called")
return x > 0
## Short-circuit example
result = False and risky_operation(10) ## Won't call risky_operation
Common Boolean Expression Patterns
Pattern |
Description |
Example |
Chained Comparisons |
Combine multiple comparisons |
0 < x < 10 |
Membership Tests |
Check if item exists |
x in list |
Identity Checks |
Compare object identity |
x is None |
Best Practices
- Use parentheses to clarify complex conditions
- Keep boolean expressions readable
- Prefer explicit comparisons
- Use meaningful variable names