Python for Programmers: Chained Inequalities
Welcome to the Chained Inequalities lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
In mathematics, we'd say that
3 < 4 < 5is true. However, that expression is false in most programming languages.In Python,
3 < 4 < 5is equivalent to(3 < 4) and (4 < 5). This is very unusual among programming languages!>
3 < 4 < 5Result:
True
This works for all infix comparison operators, not just
<. (Infix operators are operators that go between two values.) We can also chain<=,>,>=,==, and!=in the same way.>
# (1 != 2) and (2 == 2.0)1 != 2 == 2.0Result:
True
In JavaScript, and almost all other programming languages, that expression is false.
1 != 2evaluates totrue, giving ustrue == 2.0, which evaluates tofalse.We can combine several inequality tests into a single expression, but that sometimes comes at the cost of readability. Here's a comparison that decides whether
amountis less than two separate limits.>
company_spending_limit = 300personal_spending_limit = 250amount = 200# This works, but may look strange depending on your preferences.personal_spending_limit > amount < company_spending_limitResult:
True
That code works, but you may find that it looks very strange. In this case, we'd recommend two separate conditions joined with
and.>
company_spending_limit = 300personal_spending_limit = 250amount = 200(amount < personal_spending_limit) and (amount < company_spending_limit)Result:
True
When learning to program for the first time, we have to "un-learn" a lot of things, like this detail of how comparison operators work in mathematics. Later, when learning Python as a second (or seventh) language, we have to re-learn what we previously un-learned, bringing us back to natural expressions like
3 < 4 < 5.In practice, it's rare to see infix operators like
<or>chained beyond 3 values. However,a <= b <= cis a common way to quickly decide whethera,b, andcare ordered from smallest to largest.Here's a code problem:
We want to move into an apartment with a very specific size. The
apartment_size_okfunction decides whether an apartment's size meets our criteria. The criteria are:- The size must be at least "the ideal size minus 5 square meters".
- The size must be at most "the ideal size plus 10 square meters".
You don't need to use
andhere! This problem can be solved with a single chained inequality expression.def apartment_size_ok(ideal_size, size):"""Is this apartment close enough to our ideal size?Arguments are in m^2."""return (ideal_size - 5) <= size <= (ideal_size + 10)assert apartment_size_ok(50, 70) == Falseassert apartment_size_ok(50, 60) == Trueassert apartment_size_ok(60, 50) == Falseassert apartment_size_ok(60, 55) == True- Goal:
No errors.
- Yours:
No errors.