I have an integer value x, and I need to check if it is between a start and end values, so I write the following statements:
if x >= start and x <= end:
# do stuff
This statement gets underlined, and the tooltip tells me that I must
simplify chained comparison
As far as I can tell, that comparison is about as simple as they come. What have I missed here?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
In Python you can “chain” comparison operations which just means they are “and”ed together. In your case, it’d be like this:
if start <= x <= end:
Reference: https://docs.python.org/3/reference/expressions.html#comparisons
Method 2
It can be rewritten as:
start <= x <= end:
Or:
r = range(start, end + 1) # (!) if integers
if x in r:
....
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0