Sub topic 2
Choosing Among Several Cases with `elif`
Assume you can run Python scripts and understand variables, basic data types, functions, and print(). Python uses elif to test several mutually exclusive conditions.
Choosing with `elif`
An if/elif/else chain checks conditions from top to bottom. Python runs only the first branch whose condition is true. The remaining conditions are skipped.
score = 83
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade)The output is B. Although 83 >= 70 is also true, Python never reaches that test because the elif score >= 80 branch already matched.
Truthiness: Using Values as Conditions
A condition does not need to produce an explicit True or False. Python evaluates an object’s truthiness, which is whether it acts true or false in a condition.
Common falsy values include False, None, 0, "", [], and {}. Most other values are truthy.
items = []
if items:
print("has items")
else:
print("empty")Use is None when you need to distinguish a missing value from a legitimate zero or empty value.
Combining Conditions
Use and, or, and not to combine conditions. and requires both sides to be truthy. or requires at least one side to be truthy. not reverses truthiness. Use parentheses when the intended grouping is not obvious.
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("admitted")Short-Circuit Evaluation
Python stops evaluating a logical expression as soon as its result is known. With and, a falsy left side stops evaluation. With or, a truthy left side stops evaluation.
settings = {}
if settings and settings["debug"]:
print("debug on")
else:
print("debug off")Because settings is an empty, falsy dictionary, Python never evaluates settings["debug"]. This avoids a KeyError.
Exercise
What does this print: value = 0; print("ready" if value or value == 0 else "missing")?
Show answer
It prints ready. The left side of or is falsy, so Python evaluates value == 0, which is true.