Python Conditional Expressions
Learn how to choose between two values with Python’s conditional expression, while keeping the expression readable and distinct from a full if statement.
Basic
Python can choose a value without choosing a whole block of statements. A conditional expression puts the two possible values and the condition into one expression, so the result can be used wherever an expression is expected.
The basic shape
|
|
Read it as: choose "adult" if the condition is true; otherwise choose "minor".
The syntax is `value_if_true if condition else value_if_false`. Python evaluates the condition first. If it is true, the first value is evaluated and returned; otherwise the second value is evaluated and returned.
It produces a value
|
|
Because a conditional expression produces a value, you can assign it or pass it directly to another function.
This is the important difference from the `if` statement you already know: an `if` statement controls which block of statements runs, while a conditional expression computes one value.
Choose between computed values
|
|
The two alternatives can themselves be expressions, not just literal strings.
Only the selected value expression is evaluated. That makes a conditional expression useful when choosing between computations, not merely between fixed labels.
Use it inside larger expressions
|
|
A conditional expression can be one part of a larger expression.
Because the result is an ordinary value, it can participate in arithmetic, function calls, assignments, and other expressions. Keep the surrounding expression easy to read; compact syntax is not automatically better syntax.
Keep the condition easy to read
|
|
A short, clear condition can fit naturally inside the expression.
If the condition becomes difficult to understand, calculate a named boolean first or use a regular `if` statement. The goal is readable Python, not the shortest possible line.
Nested conditional expressions need care
|
|
Nested conditional expressions are legal, but parentheses and formatting help readers see the choices.
Conditional expression vs if statement
|
|
Use the expression when you need a value; use the statement when you need to control a block of work.
A good rule is simple: if the question is “which value should I use?”, a conditional expression may fit. If the question is “which work should the program perform?”, an `if` statement is usually clearer.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.