In this lesson, you will learn how to replace verbose if-else blocks with concise conditional expressions to make your loops cleaner and easier to read.
The Problem: Verbose Logic
When processing lists, we often use if-else statements to assign values based on a condition. While effective, this can create "visual clutter" that makes your loops harder to scan.
Consider this example where we categorize scores as either "Pass" or "Fail":
scores = [85, 42, 90, 30]
results = []
for score in scores:
if score >= 50:
status = "Pass"
else:
status = "Fail"
results.append(status)
The Solution: Conditional Expressions
Python offers a shorthand called a conditional expression (often called a ternary operator). Instead of spanning four lines, you can express the same logic in a single line: value_if_true if condition else value_if_false.
Let’s refactor the loop above using this technique:
scores = [85, 42, 90, 30]
results = []
for score in scores:
# A concise one-liner replacing the if-else block
status = "Pass" if score >= 50 else "Fail"
results.append(status)
Why Use This?
- Readability: By collapsing simple logic into one line, your loop’s intent becomes clearer. You aren't distracted by multiple lines of indentation just to set a simple variable.
- Maintainability: When your loop logic is compact, it is much easier to modify later without breaking the structure of your code.
- Flow: It keeps the "action" of your loop (in this case, appending to a list) visually prominent, while the "decision" logic stays compact.
While you shouldn't use this for complex, multi-line logic, it is the perfect tool for simplifying simple assignments inside your loops.
Key Takeaway: Use conditional expressions to replace basic if-else blocks with a single, readable line of code to reduce loop complexity.