# v---------- should be <
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
Python允许你用写来表达你的意思
if number in xrange(10000, 30001): # ok you have to remember 30000 + 1 here :)
在Python3中,您需要使用range而不是xrange。
编辑:人们似乎更关心微基准标记和如何酷链操作。我的答案是关于防御性编程(减少漏洞的攻击面)。
由于评论中的说法,我在这里添加了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
如果您担心性能问题,可以只计算一次范围
$ python3.5 -m timeit -s "R=range(10000, 30000)" "5 in R"
10000000 loops, best of 3: 0.0551 usec per loop
但是,只有当它不在某些性能关键路径上运行时,才建议使用range()方法。对于大多数需求来说,单个调用仍然足够快,但是如果运行10,000,000次,我们清楚地注意到与a <= x < b相比,性能要慢近3倍:
> { time python3 -c "for i in range(10000000): x = 50 in range(1, 100)"; } 2>&1 | sed -n 's/^.*cpu \(.*\) total$/\1/p'
1.848
> { time python3 -c "for i in range(10000000): x = 1 <= 50 < 100"; } 2>&1 | sed -n 's/^.*cpu \(.*\) total$/\1/p'
0.630
if 10000 <= b and b <=30000:
print ("you have to pay 5% taxes")
if 10000 <= number <= 30000:
print ("you have to pay 5% taxes")
if number in range(10000,30001):
print ("you have to pay 5% taxes")