

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: What Is Functional Programming?
incomplete
2: Why Python?
incomplete
3: Immutability
incomplete
4: Declarative Programming
incomplete
5: It's Math
incomplete
6: Classes vs. Functions
incomplete
7: Debugging FP
incomplete
8: Functional vs. OOP
incomplete
9: Statements vs. Expressions
incomplete
10: Ternary Expressions
incomplete
11: Functions Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Ternaries are a great way to reduce a series of statements, like an if/else block, to a single expression. When you first learned how to use conditional logic in Python, it probably looked like this:
result: float = 0
if number % 2 == 0:
result = number / 2
else:
result = (number * 3) + 1
This code sets result to a dummy value like 0 (None would also work), then overwrites it with its "real" value based on the condition. A ternary lets us do all that in one expression:
result: float = number / 2 if number % 2 == 0 else (number * 3) + 1
Note that we also avoided mutating the result variable! Ternary expressions are good for maintaining immutability.
The syntax for a ternary in Python is:
value_a if condition else value_b
This qualifies as an expression because it's a single statement that evaluates to a value – one of two values, depending on the condition.
Because it's an expression, you can use it anywhere a value is expected, including as a return statement:
def get_discount(is_member: bool) -> float:
return 0.1 if is_member else 0.0
Ternary expressions are cool, but don't overdo it. If you're dealing with complex conditional logic, it's often easier to work with full if/else blocks than to try to nest ternaries inside each other.
msg: str = (
"Access granted"
if (
user.is_authenticated
and (user.role == "admin" or (user.role == "editor" and not user.suspended))
)
else ("Access limited" if user.is_authenticated else "Access denied")
)
Our Doc2Doc utility is designed to accept input documents in a variety of formats. It chooses the appropriate parser for a document based on the extension of the file name. Currently, only Markdown and plain-text parsers are supported.
Fix the choose_parser function. The logic is correct, but we want to simplify the conditional block to a one-line ternary expression.