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
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 Are the parenthesis necessary or not? Because without the function works anyway.
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!”
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”)