我如何确定一个给定的整数是否在另外两个整数之间(例如大于/等于10000和小于/等于30000)?

到目前为止,我的尝试并没有奏效:

if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")

当前回答

>>> r = range(1, 4)
>>> 1 in r
True
>>> 2 in r
True
>>> 3 in r
True
>>> 4 in r
False
>>> 5 in r
False
>>> 0 in r
False

其他回答

你的代码片段,

if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")

实际上检查number是否大于10000和30000。

假设你想检查数字是否在10000 - 30000范围内,你可以使用Python的间隔比较:

if 10000 <= number <= 30000:
    print ("you have to pay 5% taxes")

这个Python特性在Python文档中有进一步的描述。

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

试试这个简单的函数;它检查A是否在B和C之间(B和C的顺序可能不对):

def isBetween(A, B, C):
    Mi = min(B, C)
    Ma = max(B, C)
    return Mi <= A <= Ma

所以isBetween(2, 10, -1)和isBetween(2, -1, 10)是一样的。

我添加了一个没有人提到的解决方案,使用symphony库中的Interval类:

from sympy import Interval

lower_value, higher_value = 10000, 30000
number = 20000

 # to decide whether your interval shhould be open or closed use left_open and right_open 
interval = Interval(lower_value, higher_value, left_open=False, right_open=False)
if interval.contains(number):
    print("you have to pay 5% taxes")

您使用>=30000,因此如果number是45000,它将进入循环,但我们需要它大于10000但小于30000。将其更改为<=30000就可以了!