Branching
if, elif and else run the first block whose condition is true. Indentation marks the block.
def label(n):
if n < 0:
return "negative"
elif n == 0:
return "zero"
else:
return "positive"Truthiness
Any value can be a condition. These count as false: 0, 0.0, "", [], {}, None and False. Almost everything else is true.
Combining conditions
and,orandnotcombine conditions and stop as soon as the answer is known.- Comparisons chain:
0 < x <= 10means0 < x and x <= 10. a if condition else bis an expression, handy for short choices.
Conditions are checked from top to bottom. Order them so that an earlier test does not swallow a case meant for a later one. Boundaries are where most branching bugs live, so test them first.
Your task
Write shipping_cost(weight_kg, express=False): 0 for weight 0 or less, 5 up to and including 1 kg, 9 up to and including 5 kg, 15 above that, and express doubles the price. Write is_leap(year) for the Gregorian rule: divisible by 4, except centuries, unless divisible by 400.
The explanation opens here once every check passes.