Conditional Expressions
Sometimes an entire if/else block exists only to pick one of two values. In this lesson you will learn the conditional expression, Python's one-line way to do exactly that.
You already know how to pick a value with if and else. Sometimes the only thing the branches do is set one variable, and writing four lines for that feels heavy.
Here is a typical example: pick a label based on age.
Python lets you write the same idea on a single line using a conditional expression, often called a ternary expression.
The shape is always the same:
Here is the age example rewritten as one line.
Read it left to right, like English: 'adult' if age is 18 or more, else 'minor'. The condition sits in the middle, the two possible values sit on the outside.
It works for numbers too. Here we pick the larger of two values.
What will be the output?
A conditional expression is just a value, so you can drop it straight into a print() call.
What will be the output?
It also works with booleans directly. No comparison is needed when the variable is already True or False.
Use a conditional expression when both branches just produce a value. If the branches need to do several things, stick with a normal if/else block. The goal is to keep code easy to read, not to make it shorter at any cost.
What will be the output?
What will be the output?
What will be the output?