Python Glossary Русский

all Python 3Conditionalsconstruct

Conditional expression (ternary)

branching

The compact one-line form of if-else. It returns one of two values depending on the condition. Read it as: value_if_true if condition else value_if_false.

Syntax

значение_если_истина if условие else значение_если_ложь

Unlike a regular if, this is an expression — it returns a value, so you can drop it right where a statement isn't allowed: a function argument, an f-string, a comprehension body. The order is unusual (result first, condition second), and stacking nested ternaries to fake an elif quickly wrecks readability.

Examples

x = 7
result = "чётное" if x % 2 == 0 else "нечётное"
print(result)  # → нечётное
a, b = 3, 9
bigger = a if a > b else b
print(bigger)  # → 9
n = -5
abs_n = n if n >= 0 else -n
print(abs_n)  # → 5
age = 20
status = "совершеннолетний" if age >= 18 else "несовершеннолетний"
print(status)  # → совершеннолетний
lst = [1, 2, 3]
print("есть" if lst else "пусто")  # → есть
name = None
print(name if name else "Гость")  # → Гость

See also

Open in the full glossarydocs.python.orgReport an inaccuracy