Python Comparison Chaining Explained (0 < amount < balance) with Examples
Learn Python comparison chaining with simple examples. Understand how expressions like 0 < amount < balance work, including evaluation steps, short-circuiting, and benefits for beginners.
Comparison Chaining in Python
In Python, the expression:
0 < amount < balanceis an example of comparison chaining.
It allows you to write multiple conditions in a single, clean statement—just like in mathematics (e.g., “amount is between 0 and balance”).
How Python Evaluates It
Python internally treats:
0 < amount < balanceas:
(0 < amount) and (amount < balance)Step-by-Step Logic
-
First Check: Python checks if
0 < amount. -
Short-Circuiting:
- If this is False, Python stops immediately.
- The second condition is not checked.
-
Second Check: If the first condition is True, Python checks if
amount < balance. -
Final Result:
- If both conditions are True, the result is True.
- Otherwise, the result is False.
Why Use Comparison Chaining?
✅ 1. Better Readability
- Matches mathematical expressions
- Easy to understand: “amount is between 0 and balance”
✅ 2. More Efficient
-
The middle value (
amount) is evaluated only once -
Useful when using functions:
0 < get_amount() < balance
Examples
| Scenario | Values | Result |
|---|---|---|
| Valid Range | amount = 50, balance = 100 |
True |
| Zero or Negative | amount = 0, balance = 100 |
False |
| Exceeds Balance | amount = 150, balance = 100 |
False |
Important Note (Other Languages)
In languages like C++ or Java, writing:
0 < amount < balancecan give incorrect results.
Why?
- First,
0 < amountis evaluated → givestrueorfalse - Then, that boolean is compared with
balance→ which is not intended
👉 Python is different: It understands the chain and evaluates it correctly as a combined condition.
Quick Tip
You can chain multiple comparisons:
0 < amount < balance < limitThis is equivalent to:
(0 < amount) and (amount < balance) and (balance < limit)