Learn with Yasir

Share Your Feedback

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 < balance

is 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 < balance

as:

(0 < amount) and (amount < balance)

Step-by-Step Logic

  1. First Check: Python checks if 0 < amount.

  2. Short-Circuiting:

    • If this is False, Python stops immediately.
    • The second condition is not checked.
  3. Second Check: If the first condition is True, Python checks if amount < balance.

  4. 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 < balance

can give incorrect results.

Why?

  • First, 0 < amount is evaluated → gives true or false
  • 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 < limit

This is equivalent to:

(0 < amount) and (amount < balance) and (balance < limit)


🧠 Practice & Progress

Explore More Topics

📘 Learn Python

Tutorials, Roadmaps, Bootcamps & Visualization Projects

Python Fundamentals

Flow Control Statements


Python Functions


Fundamentals more ...




🧠 Python Advanced

Object-Oriented Programming in Python (OOP)

More...

🧠 Modules