Conditionals I

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
Output

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:

Python

Here is the age example rewritten as one line.

Python
Output

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.

Python
Output

What will be the output?

Python

A conditional expression is just a value, so you can drop it straight into a print() call.

Python
Output

What will be the output?

Python

It also works with booleans directly. No comparison is needed when the variable is already True or False.

Python
Output

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?

Python

What will be the output?

Python

What will be the output?

Python