Ad space (banner)
🐍Python Lessons
Lesson 16 / 69

The Conditional (Ternary) Expression

This lesson covers Python's conditional expression (often called a ternary operator), so you can express a simple branch concisely in a single line. It's written for anyone searching "Python ternary operator syntax".

Python lets you write a simple if statement in one line, in the order value_if_true if condition else value_if_false. It's well suited to short branches, like "decide on the spot whether someone is an adult or a minor." Notice the word order is different from something like JavaScript's condition ? true_value : false_value — a distinctly Python touch.

The sample code uses the conditional expression "Adult" if age >= 20 else "Minor" to decide what string to assign to the message variable based on age. Because it uses the actual English words if and else, it reads more like a natural sentence than the ternary operator in many other languages.

Packing too much logic into a conditional expression makes it harder to read, so the trick to writing clean code is reserving it for simple, two-way decisions. It's frequently paired with a variable assignment, which helps keep code compact.

In real development, conditional expressions come up constantly for small value swaps — choosing which text to display based on a condition, or transforming a value inside a list comprehension.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)