Can transitively related expressions (like a < b and b < c) be shortened?

Question

If we have a transitive relation of expressions combined with and, like (a < b) and (b < c) and (c < d), can this be shortened?

Answer

Yes, this can be done by chaining the expressions with a transitive relation. Because of the order of operations, each and operator has the same precedence which means that they will just evaluate from left to right as they appear in the entire expression.

Example

a = 1
b = 2
c = 3
d = 4

# Original expression
(a < b) and (b < c) and (c < d) # True

# Using chaining, we can shorten this.
# This will evaluate to the same result as above
a < b < c < d # True
19 Likes

5 posts were split to a new topic: What is the order of operations for logical operators?

Hi I’m not sure 100% if this is the exact right place but I see in this post the explanation of the chain of the related expressions.
In the last exercise is required to modify the function in this snippet and add a "and operator and this was my code :

def graduation_reqs(credits,gpa):
if credits >= 120 and gpa >= 2.0:
return “You have enough credits to graduate!”

If I run this snippet I get an error: " Expected graduation_reqs() with test values gpa = 2.0 and credits = 120 to return “You meet the requirements to graduate!”

I took a peek in the solution I saw that the difference was:
def graduation_reqs(credits,gpa):
if (credits >= 120) and (gpa >= 2.0):
return “You have enough credits to graduate!”

I don’t want bother anyone but only understand :slight_smile: Are the parenthesis necessary or not? Because without the function works anyway.

Thank you very much

Hey, the following code worked for me:
def graduation_reqs(credits,gpa):
if credits >= 120 and gpa >= 2.0:
return “You meet the requirements to graduate!”

The parenthesis aren’t necessary then I guess. It probably didn’t work for you with your original code as you had mistakenly tried to return the string “You have enough credits to graduate!” instead of “You meet the requirements to graduate!”