Python checks an if condition first, then checks each elif in order until one is true. It runs the first matching branch and skips the rest. The optional else runs only when all the conditions are false. Use separate if statements when more than one action can apply.
def status(completed, total):
if total == 0:
return "Nothing scheduled"
elif completed == total:
return "Complete"
else:
return "In progress"
assert status(0, 0) == "Nothing scheduled"
assert status(3, 3) == "Complete"
assert status(2, 3) == "In progress"
The zero-total case comes first so an empty plan gets its own label. If completed == total came first, zero out of zero would be labeled “Complete.”
Decide whether cases are mutually exclusive
Use an if / elif / else chain when you want the first matching branch to decide the outcome. Use separate if statements when more than one action may be valid. A report that labels a request “late” and “needs review” might require both. Classifying a value into exactly one bucket needs a different shape.
For numeric bands, put the most specific overlapping case first. If you write if score >= 50 followed by elif score >= 90, the second branch will never run. List a few representative values and trace the branch order before assuming the conditions express the intended rule.
Use explicit comparisons at boundaries
A test such as 0 <= hours < 24 makes the intended interval apparent. This comparison includes zero and excludes 24. When the business rule says “through 24” or “before the due date,” translate it into a representative example at the exact boundary. It is easier to spot an error in a result for hours = 24 than in an isolated < sign.
Use == to compare values and = to assign a name. Writing if name = "Mina": is a syntax error. Use is None when you specifically mean the None object, and == when you care about ordinary value equality.
Keep missing values and false values distinct
An empty string, zero, and None are all false in a condition. Their meaning can differ. If a missing measurement is represented by None, a test of if not measurement would also treat a genuine zero as missing. Write if measurement is None for that rule.
When combining conditions, and skips the right side if the left side is false. This makes value is not None and value > 0 safe when the only possibilities are numbers and None. It does not validate that a supplied string is numeric. Parse and validate external input before asking conditions to do domain work.
Combine conditions with and and or
The expression if role == "editor" or "owner": always enters the branch for an ordinary string role. A match makes the first test true. With any other role, the nonempty string "owner" itself is true in a condition. Compare explicitly with role == "editor" or role == "owner", or use role in {"editor", "owner"}.
Parentheses help when readers need to see the grouping. is_active and (is_owner or is_editor) requires an active account for either role. (is_active and is_owner) or is_editor has another meaning. Give the expression a name or split the check into steps when the policy needs explanation in its own right.
Use a conditional expression for one value
Python also supports value_if_true if condition else value_if_false as an expression. This is useful when a single result needs a default or a label. In a program that prints a report, an expression such as "entry" if count == 1 else "entries" supplies the word without spreading the choice across separate assignments.
A statement is often clearer when a branch does several things, such as updating a record and recording that update. Avoid nesting several conditional expressions when you could name the separate cases with if and elif. A reader should be able to see the test without mentally unwrapping the expression.
Reduce nesting when a branch rejects an input
Consider a function that checks whether a label can be used in a table. When some checks rule out further work, an early return can make the supported case easier to follow.
def clean_label(value):
if not isinstance(value, str):
return None
text = value.strip()
if not text:
return None
return text
assert clean_label(" Room 2 ") == "Room 2"
assert clean_label(" ") is None
assert clean_label(0) is None
The first check makes it clear why strip() is available on the next line. The second check decides how this function treats blank strings. Combining them into one branch could be fine, but separation gives each rule an obvious place to change. If callers need to distinguish unsupported type from blank content, consider returning a richer result or raising specific exceptions.
Check the cases someone will actually exercise
Start with one case per branch, then test the exact boundaries where the output changes. If multiple conditions can be true, test the overlap. Decide what input the function accepts before building test cases for invalid data. In the opening example, the function assumes 0 <= completed <= total. A production caller should enforce that rule or give invalid inputs their own explicit response.
Avoid silently sending an unrecognized state through an else that was intended for a known state. If only “ready” and “waiting” are valid, name both when malformed data can arrive. The final branch can then report an unfamiliar value instead of quietly recategorizing it.