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

1 Like

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!”

4 Likes

hi can anyone please tell me what am doing wrong
so the idea behind this is to have the user input number not less than 2 and not greater than 30 which is what I did and I use the and statement but it still comes back as a syntax error

lawn_widthmin = input(“enter the lawn meter”)
#use the if statement to meet the condition
if lawn_widthmin >=2 and <=30:
print(“cone”)
else:
print(“not right”)

That expression implies a value in between. If a is 2, b is the number in between, and c is 30, following the example given in the OP, we have,

a <= b <= c

as in,

2 <= b <= 30

in which case, lawn_width is b.

thanks for that i get it now

1 Like

Hi!
I think you’re getting a Syntax Error because the if is not well formulated.
It should be

if lawn_widthmin >=2 and lawn_widthmin <=30: