All coding lessonsLesson 4 of 10

Control Flow: if, elif, else

Making decisions and the meaning of indentation

Programs become useful when they react to data. The if statement runs a block of code only when a condition is true.

temperature = 31

if temperature > 30:
    print("It is hot")
elif temperature > 20:
    print("Pleasant")
else:
    print("Bring a jacket")

Indentation is syntax, not decoration

Where other languages use { }, Python uses indentation to group statements into a block. The standard is four spaces per level. Mixing tabs and spaces causes an IndentationError or, worse, code that runs but is grouped wrongly.

elif chains

Python checks the branches in order and executes only the first one whose condition is true. Once a branch runs, the rest are skipped — so put the most specific condition first.

score = 87

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)  # B

Conditional expressions

age = 15
label = "adult" if age >= 18 else "minor"
print(label)  # minor

Membership and identity

vowels = "aeiou"
letter = "k"
if letter not in vowels:
    print("consonant")

value = None
if value is None:
    print("no value yet")

Use is only for comparing with None, True and False — it asks whether two names point to the same object, not whether they are equal.

Ask Teacher Smith questions about this Python lessonOpens your AI tutor with a question about “Control Flow: if, elif, else” →