Concept Flow - Ternary conditional expression
Evaluate condition
Yes
Use value if True
End
No
Use value if False
End
The ternary expression first checks a condition. If true, it returns the first value; otherwise, it returns the second value.
Jump into concepts and practice - no test required
x = 10 result = "Even" if x % 2 == 0 else "Odd" print(result)
| Step | Condition (x % 2 == 0) | Result | Value Chosen | Output |
|---|---|---|---|---|
| 1 | 10 % 2 == 0 | True | "Even" | "Even" |
| 2 | Print result | - | - | Even |
| Variable | Start | After Step 1 | After Step 2 |
|---|---|---|---|
| x | 10 | 10 | 10 |
| result | undefined | "Even" | "Even" |
Ternary conditional expression syntax: value_if_true if condition else value_if_false It evaluates the condition first. If True, returns value_if_true. If False, returns value_if_false. Useful for simple if-else in one line.
x if condition else y do in Python?x if condition else y means Python checks the condition.condition is True, it returns x; if False, it returns y.x if condition is True, otherwise returns y. -> Option Cx if condition else y for ternary expressions.age = 20 status = "Adult" if age >= 18 else "Minor" print(status)
age >= 18 is True because age is 20.status is assigned "Adult".result = "Pass" if score > 50 else "Fail" else "Invalid"
else keywords, which is invalid syntax in Python ternary expressions.else part; multiple else cause SyntaxError.{key: value for variable in iterable}. The value can use a ternary expression.else keyword, causing SyntaxError; d = {x if x % 2 == 0 else "Odd": x for x in range(1,6)} misplaces ternary in key. d = {x: "Even" else "Odd" if x % 2 == 0 for x in range(1,6)} has invalid syntax.