all Python 3Conditionalsconstruct
Nested conditions
branching
An if inside another if. It lets you test combinations of conditions. Use it carefully — deep nesting hurts readability.
Syntax
if условие1:
if условие2:
блок
Nesting is often a hint to simplify: two ifs in a row without an else collapse into one via and, and deep branches flatten out with an early return or continue that strips the extra levels. This is a case where flat code almost always reads better than nested.
Examples
x = 15
if x > 0:
if x % 2 == 0:
print("положительное чётное")
else:
print("положительное нечётное") # → положительное нечётное
age, has_ticket = 20, True
if age >= 18:
if has_ticket:
print("вход разрешён") # → вход разрешён
n = 100
if n >= 10:
if n <= 999:
print("двух/трёхзначное") # → двух/трёхзначное
a, b = 5, 10
if a > 0:
if b > 0:
if a + b > 12:
print("сумма > 12") # → сумма > 12
See also
Open in the full glossarydocs.python.orgReport an inaccuracy