Complex Conditions
Advanced Condition Techniques
Complex conditions in Python allow for sophisticated decision-making and more nuanced program logic beyond simple comparisons.
Nested Conditions
def classify_student(age, grades):
if age >= 18:
if grades > 90:
print("Excellent adult student")
elif grades > 70:
print("Good adult student")
else:
print("Adult student needs improvement")
else:
if grades > 85:
print("Promising young student")
elif grades > 60:
print("Average young student")
else:
print("Young student needs support")
Conditional Expressions (Ternary Operators)
## Simplified conditional assignment
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Membership and Identity Conditions
## Checking membership
fruits = ['apple', 'banana', 'cherry']
print('apple' in fruits) ## True
print('grape' not in fruits) ## True
## Identity comparison
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x is z) ## True
print(x is y) ## False
print(x == y) ## True
Condition Flow Complexity
graph TD
A[Start] --> B{Primary Condition}
B -->|True| C{Secondary Condition}
B -->|False| G[Alternative Path]
C -->|True| D[Complex Action 1]
C -->|False| E{Tertiary Condition}
E -->|True| F[Complex Action 2]
E -->|False| G
Advanced Condition Techniques
Technique |
Description |
Example |
Walrus Operator |
Assignment within condition |
if (n := len(items)) > 10: |
Multiple Conditions |
Chained logical checks |
if 0 < x < 10 |
Conditional Comprehensions |
Conditional list generation |
[x for x in range(10) if x % 2 == 0] |
Error Handling with Conditions
def safe_divide(a, b):
try:
result = a / b if b != 0 else None
return result
except TypeError:
return "Invalid input"
Best Practices
- Keep conditions readable
- Use parentheses for complex logic
- Avoid deeply nested conditions
- Prefer early returns
LabEx encourages developers to practice these advanced condition techniques to write more elegant and efficient Python code.