Conditionals
A conditional statement selects which block of code runs based on the truth of
an expression. if introduces the first condition, elif adds further
conditions tested in order, and else supplies a fallback. At most one branch
executes: once a condition is satisfied, the remaining branches are skipped.
adequate
Because evaluation stops at the first true condition, the order of the branches
is part of the logic. If depth >= 30 were tested first, a depth of 120 would
report "adequate", since that condition is also true. Order conditions from
most specific to least specific.
Comparison and boolean operators
The comparison operators are ==, !=, <, <=, > and >=. Note that
== tests equality of value, whereas is tests object identity to determine
whether two identifiers reference the identical object in memory. Use is only with None, True and False.
Comparisons may be chained: 30 <= depth <= 100 is evaluated as
30 <= depth and depth <= 100, with depth evaluated once.
True True True
and and or are short-circuiting. and stops at the first false operand and
or at the first true one, and both return the operand rather than a boolean.
This permits guarding an expression that would otherwise raise, as in
values and sum(values) / len(values).
Truth value testing
Any object may be tested for truth. Numeric zero, the empty string, the empty
list, the empty dictionary and None are false. Non-empty containers and
non-zero numbers are true.
'' False 'ATG' True [] False [1] True 0 False 1 True None False
Consequently if not sequence: is the conventional test for an empty string,
and is preferred to if len(sequence) == 0:. Take care when zero is a
meaningful value: if depth: treats a depth of 0 as absent, whereas
if depth is not None: does not.
Conditional expressions
When both branches produce a value, the expression form assigns directly. It is appropriate for short alternatives and should not be nested.
pass
Task
Write classify(depth, quality). Both arguments are integers. Return:
"FAIL"if depth is below 10, or quality is below 20."HIGH"if depth is 100 or more and quality is 30 or more."PASS"in all other cases.
Test the failing condition first and return from it immediately. The later branches are then guaranteed to operate on values that passed the minimum thresholds, which removes the need to repeat those checks.
Test cases · 4
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | 5 40 | FAIL |
| 2 | stdin | 120 35 | HIGH |
| 3 | stdin | 45 25 | PASS |
| 4 | stdin | 150 22 | PASS |
Hints · 2
01Hint
Return early from the FAIL branch so later branches only see valid input.
02Hint
Combine the two FAIL conditions with `or`.