Determine Whether Integer Is Between Two Other Integers?

前端 未结 11 860
猫巷女王i
猫巷女王i 2020-11-22 15:07

How do I determine whether a given integer is between two other integers (e.g. greater than/equal to 10000 and less than/equal to 30000)?

I\

11条回答
  •  无人及你
    2020-11-22 15:47

    The trouble with comparisons is that they can be difficult to debug when you put a >= where there should be a <=

    #                             v---------- should be <
    if number >= 10000 and number >= 30000:
        print ("you have to pay 5% taxes")
    

    Python lets you just write what you mean in words

    if number in xrange(10000, 30001): # ok you have to remember 30000 + 1 here :)
    

    In Python3, you need to use range instead of xrange.

    edit: People seem to be more concerned with microbench marks and how cool chaining operations. My answer is about defensive (less attack surface for bugs) programming.

    As a result of a claim in the comments, I've added the micro benchmark here for Python3.5.2

    $ python3.5 -m timeit "5 in range(10000, 30000)"
    1000000 loops, best of 3: 0.266 usec per loop
    $ python3.5 -m timeit "10000 <= 5 < 30000"
    10000000 loops, best of 3: 0.0327 usec per loop
    

    If you are worried about performance, you could compute the range once

    $ python3.5 -m timeit -s "R=range(10000, 30000)" "5 in R"
    10000000 loops, best of 3: 0.0551 usec per loop
    

提交回复
热议问题