Simplify Chained Comparison

前端 未结 3 1268
你的背包
你的背包 2020-11-27 02:28

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:



        
相关标签:
3条回答
  • 2020-11-27 02:57

    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

    0 讨论(0)
  • 2020-11-27 03:17

    Simplification of the code

    if start <= x <= end: # start x is between start and end 
    # do stuff
    
    0 讨论(0)
  • 2020-11-27 03:24

    It can be rewritten as:

    start <= x <= end:
    

    Or:

    r = range(start, end + 1) # (!) if integers
    if x in r:
        ....
    
    0 讨论(0)
提交回复
热议问题