Conditional Assignment
Concepts covered: Ternary Expression
Many branches exist only to give a single variable one of 2 values. Written as a 4-line if/else, the reader has to confirm that both arms assign the same name. A conditional expression moves the choice to the right side of a single assignment, so the name appears once.
if order_total >= 100:
shipping = 0.0
else:
shipping = 7.5
shipping = 0.0 if order_total >= 100 else 7.5The form is value_if_true if condition else value_if_false. Python evaluates the condition first, then evaluates only the side it picked. The else part is required: shipping = 0.0 if order_total >= 100 is a SyntaxError, because an expression must produce a value in every case. Since the whole thing is an expression, it can sit anywhere a value can, such as on the right of = or inside print(). It also works after return.
order_total = 64.0
shipping = 0.0 if order_total >= 100 else 7.5
print(shipping)
count = 0
total = 0
avg = total / count if count != 0 else 0.0
print(avg)
raw_country = None
country = raw_country if raw_country is not None else "unknown"
print(country)
print("free" if shipping == 0.0 else "paid")Output:
7.5 0.0 unknown paid
The average line depends on Python evaluating only the chosen side. With count at 0 the condition is False, so total / count never runs and no ZeroDivisionError appears. The country line is the standard way to default a missing value: test is not None, and keep the real value whenever there is one.
Precedence: the if takes everything to its left
A conditional expression binds more loosely than arithmetic and comparisons. In base + 5 if express else 0, Python takes all of base + 5 as the true side, so the result is either the whole sum or 0. To add 5 only for express orders, wrap the conditional in parentheses: base + (5 if express else 0).
What does this print?
base = 20
express = False
price = base + 5 if express else 0
print(price)- 20, because the conditional only decides whether 5 is added to base.
- 25, because base + 5 is computed before the condition is checked.
- 0, because base + 5 is the true side and express is False.
- A SyntaxError, because a conditional cannot follow an arithmetic operator.
Where the inline form stops paying off
Conditional expressions can chain: "gold" if spend >= 1000 else "silver" if spend >= 200 else "bronze" picks among 3 tiers, testing left to right. That is about the limit. A fourth tier, or an and inside a condition, turns the line into a puzzle, and an if/elif ladder assigning tier in each arm reads faster. Side effects fit badly too: print("a") if x else print("b") runs, but it is a statement wearing an expression's syntax.
- Good fit for an inline conditional
- 2 outcomes, each a plain value
- A default for a value that might be None
- A guard against dividing by zero
- A label passed straight into print or return
- Better as an if statement
- 3 or more outcomes, or conditions joined with and/or
- Branches that print or write a log line
- Arms that each need more than 1 line
- A choice someone will step through while debugging
Give the conditional part its own name
A conditional most often lands inside a sum when the code computes a fee or a discount, and taxes hit the same problem. Either wrap it in parentheses, or compute it on its own line first: fee = 7.5 if order_total < 100 else 0.0, then total = order_total + fee. The second form leaves no precedence to reason about, each line holds a single decision, and a debugger shows fee as its own value. With order_total at 64.0, fee is 7.5 and total is 71.5; at 120.0, fee is 0.0 and total is 120.0.
About this lesson
This section is part of the Control Flow: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.