01 / 20

Avoiding Conditional
Bugs in Python

Learn to write bulletproof conditionals by mastering condition order, boundary checks, and the subtle traps that cause silent failures in your code.

Python

What Is a Conditional Bug?

A conditional bug is a logic error in an if/elif/else chain that causes your program to take the wrong branch. The code runs without crashing, but it produces incorrect results for certain inputs.

The Two Root Causes

Wrong Condition Order
A broad condition fires before a specific one, swallowing inputs that should have been handled differently.
Missing Boundary Check
The code uses \(<\) when it should use \(<=<\/b>, so the exact boundary value lands in the wrong branch.

Why Does Condition Order Matter?

Python evaluates if/elif chains top to bottom and executes only the first branch whose condition is True. It then skips all remaining branches, even if later conditions are also true.

Input arrives if cond_1? True Run A False elif cond_2? True Run B False else: Run C

The Golden Rule of Condition Order

1
List every condition your chain must handle.
2
Check for subset relationships: Does one condition's True set lie inside another's?
3
Put the subset first. The broader condition goes later (or becomes the else).

Boundary Checks: \(<\) vs \(<=<\/span>

A boundary check bug happens when you use \(<\) instead of \(<=<\/b> (or \(>\) instead of \(>=<\/b>). The exact boundary value falls through to the wrong branch.

0 60 100
\(score < 60\): Fail
\(score \ge 60\): Pass
Boundary: where does 60 go?

Overlap vs Gap in Conditions

Overlap Bug
Two conditions can both be True for the same input. Only the first fires, silently hiding the second.
Gap Bug
No condition covers a particular input, so it falls to else (or is missed entirely if there is no else).
Overlap Gap
Cause Conditions share a subset No condition covers boundary
Symptom Wrong branch executes Unexpected else / no action
Fix Narrow conditions or reorder Add missing \(<=<\/b> or extra elif

A Step-by-Step Debugging Checklist

1
Read each condition top to bottom. For every branch, ask: "What range of inputs makes this True?"
2
Check for overlap. Can any input satisfy two conditions simultaneously? If yes, the first one wins: is that correct?
3
Check for gaps. Are there inputs that fail every condition? If no else exists, those inputs are silently ignored.
4
Test boundary values. Plug in the exact cutoff numbers. Does each one land in the intended branch?
5
Verify with extremes. Test with the smallest, largest, zero, negative, and empty/None inputs.

Example 1: Buggy Grade Assignment

✕ Buggy Code
def grade(score):
  if score >= 60: # Too broad: catches 60-100
    return "D"
  elif score >= 70: # Never reached for 70-100!
    return "C"
  elif score >= 80:
    return "B"
  elif score >= 90:
    return "A"
  else:
    return "F"

Example 1: Fixed Grade Assignment

✓ Fixed Code
def grade(score):
  if score >= 90: # Most specific first
    return "A"
  elif score >= 80:
    return "B"
  elif score >= 70:
    return "C"
  elif score >= 60: # Most general last
    return "D"
  else:
    return "F"

Example 2: Off-by-One Boundary Bug

✕ Buggy Code
def ticket_price(age):
  if age < 12: # Child: 0-11
    return 5
  elif age < 65: # Adult: 12-64
    return 12
  elif age > 65: # Senior: 66+
    return 8
✓ Fixed Code
def ticket_price(age):
  if age < 12:
    return 5
  elif age < 65:
    return 12
  else: # 65+: catches boundary!
    return 8

Example 3: isinstance Ordering Trap

In Python, bool is a subclass of int. This means isinstance(True, int) returns True. If you check for int before bool, booleans are misclassified.

✕ Buggy Code
def classify(val):
  if isinstance(val, int): # Catches bool too!
    return "integer"
  elif isinstance(val, bool): # Never reached
    return "boolean"
✓ Fixed Code
def classify(val):
  if isinstance(val, bool): # Specific subclass first
    return "boolean"
  elif isinstance(val, int):
    return "integer"

Example 4: Compound Condition Pitfall

When combining and / or, operator precedence and short-circuit evaluation can hide bugs.

✕ Buggy Code
# Intent: allow ages 13-17 OR users with parental consent
if age >= 13 and age <= 17 or has_consent:
  print("Access granted")
✓ Explicit Parentheses
if (age >= 13 and age <= 17) or (age < 13 and has_consent):
  print("Access granted")

Common Mistakes to Watch For

✕ Broad Before Specific
Checking \(x > 0\) before \(x > 100\) means the larger values never reach the specific branch.
✕ Forgetting the Boundary
Using \(<\) and \(>\) with no \(=\) leaves the exact cutoff value unhandled.
✕ No else Clause
Omitting else means unexpected inputs silently produce None instead of an error or default.

Bug Pattern Summary Table

Pattern Bug Fix
Order of conditions Broad condition first Most specific first
Boundary value \(<\) instead of \(<=<\/td> Decide which branch owns the boundary
Gap in ranges Value matches no branch Add else or adjust operators
Subclass check Parent class before child Check child class first
Compound logic Missing parentheses Use explicit parentheses

Question 1 of 5

What does this code print when \(x = 150\)?

Question 2 of 5

What does fee(18) return?

Question 3 of 5

In Python, isinstance(True, int) returns True. To correctly distinguish booleans from integers, which should you check first?

Question 4 of 5

Which fix best prevents a gap bug in a series of numeric conditions?

Question 5 of 5

Is this code correct, or does it contain a conditional bug?