Teaching a Program to Choose
A program that always does the same thing is not a program, it is a constant. Feed one input through a chain of conditions and watch exactly one branch of it ever run.
A program that always does the same thing is not a program, it is a constant. Feed one input through a chain of conditions and watch exactly one branch of it ever run.
A program that chooses
if age >= 18: print("adult")else: print("not an adult")if tests a condition. If it is true, the indented block underneath runs and Python skips the else entirely. If it is false, the if block is skipped and the else runs instead. Never both.
elif is not a second if
Stack two separate if statements and Python checks both of them, every time, even after the first one already matched. elif checks only if everything above it was false — and the moment one branch matches, every branch after it is skipped without being evaluated at all.
if age >= 18:
print("adult")elif age >= 13:
print("teenager")else:
print("child")age >= 18 is false, so Python checks the elif. age >= 13 is true, so this branch runs and the else is skipped.
What Python accepts in place of true or false
A condition does not have to be written as a comparison. Any value can sit after if, and Python converts it to True or False the same way bool() would.
$ >>> name = ""$ >>> if name:$ ... print("has a name")$ ... else:$ ... print("empty")$ emptyKey takeaways
- Exactly one branch of an if/elif/else chain runs. Once one matches, everything after it is skipped.
- elif only gets checked if every condition above it was false — unlike a stack of separate if statements.
- Any value can act as a condition; Python converts it to True or False the same way bool() would.
- Python's boolean operators are the words and, or, and not, not symbols.