Simplify Chained Comparison

2020-01-25 05:26发布

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?

3条回答
祖国的老花朵
2楼-- · 2020-01-25 05:29

It can be rewritten as:

start <= x <= end:

Or:

r = range(start, end + 1) # (!) if integers
if x in r:
    ....
查看更多
迷人小祖宗
3楼-- · 2020-01-25 05:30

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

查看更多
够拽才男人
4楼-- · 2020-01-25 05:38

Simplification of the code

if start <= x <= end: # start x is between start and end 
# do stuff
查看更多
登录 后发表回答