An if statement runs an indented block only when its condition is true. Python also accepts non-Boolean values as conditions; a value treated as true in this context is called truthy. We will examine examples in the next lesson. A colon ends the header; four spaces are the conventional indentation for each level. The following code after the block runs regardless unless control has left the function or an exception occurs.
temperature = 31
if temperature > 30:
print("Cooling requested")
print("Reading recorded")
Cooling requested
Reading recorded
If the temperature were 30, only Reading recorded would print. Indentation is structure, not decoration: moving a line out of the block changes when it runs.
Select one of several paths
elif means “else if.” Python tests each condition in order, runs the first matching block, and skips the rest. An optional else handles the remaining case.
seats = 3
if seats == 0:
print("Full")
elif seats <= 5:
print("Few seats left")
else:
print("Seats available")
Few seats left
The second test is reached only after seats == 0 is false. This example assumes a nonnegative seat count. Branch order matters when conditions overlap: testing seats <= 5 first would also catch zero. else needs no condition, and elif or else must follow an if in the same chain. Independent if statements are different: more than one can run.