all Python 3Conditionalsconstruct
if-else
branching
A two-branch conditional. If the condition is true the if block runs, otherwise the else block.
Syntax
if условие:
блок1
else:
блок2
When both branches just assign to one variable, the ternary conditional expression "A if condition else B" is tighter — the same choice in one line instead of a four-line if-else. Keep the full if-else for branches that do several things.
Examples
x = -3
if x >= 0:
print("неотрицательное")
else:
print("отрицательное") # → отрицательное
n = 7
if n % 2 == 0:
print("чётное")
else:
print("нечётное") # → нечётное
s = ""
if s:
print("не пусто")
else:
print("пусто") # → пусто — пустая строка ложна
# Однострочная форма — условное выражение
val = None
result = val if val is not None else 0
print(result) # → 0
See also
Open in the full glossarydocs.python.orgReport an inaccuracy