all Python 3Conditionalsconstruct
if
branching
The conditional statement. It runs a block of code if the condition is true. The condition is any expression Python converts to a bool.
Syntax
if условие:
блок
The condition need not be a comparison: an empty list, 0, None and "" are all falsy on their own, so "if lst:" reads as "the list is non-empty". Because of that, "if x:" and "if x is not None:" differ — 0 or an empty string fail the first but pass the second.
Examples
x = 5
if x > 0:
print("положительное") # → положительное
if "Python" in "Я учу Python":
print("нашли") # → нашли
# Пустая коллекция и None — ложь
lst = [1, 2, 3]
if lst:
print("список не пуст") # → список не пуст
name = None
if name is None:
name = "Гость"
print(name) # → Гость
# Вложенный if
x = 5
if x > 0:
if x < 10:
print("однозначное") # → однозначное
See also
Open in the full glossarydocs.python.orgReport an inaccuracy