← All lessons

The ternary operator

Sign in · Sign up

Lesson 2.7

A simple if/else that picks one value can be written on a single line:

status = "adult" if age >= 18 else "child"

It reads left to right like this: the value if the condition is true — if — the condition — else — the value if it is false.

This is the same as:

if age >= 18:
    status = "adult"
else:
    status = "child"

age is set by the check. Put the word "adult" in the variable status if the age is 18 or more, and "child" otherwise. Then print status.

Hint

The ternary operator reads left to right: what to return if yes, then the condition, then what if no.

Both branches are strings in quotes, so if holds one of them.