539

特定の整数が他の 2 つの整数の間にあるかどうかを判断するにはどうすればよいですか (たとえば、より大きい/等しい、10000およびより小さい/等しい30000)。

私は2.3 IDLEを使用していますが、これまでに試みたことが機能していません:

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

15 に答える 15

1359
if 10000 <= number <= 30000:
    pass

詳細については、ドキュメントを参照してください。

于 2012-11-29T15:13:36.087 に答える
59

オペレーターが正しくありません。する必要がありますif number >= 10000 and number <= 30000:。さらに、Python には、この種のものの省略形if 10000 <= number <= 30000:.

于 2012-11-29T15:13:34.733 に答える
34

あなたのコードスニペット、

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 ドキュメント で詳しく説明されています。

于 2012-11-29T15:13:43.100 に答える
12
if number >= 10000 and number <= 30000:
    print ("you have to pay 5% taxes")
于 2012-11-29T15:13:04.877 に答える
9

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
于 2015-11-16T22:52:36.470 に答える
1

数値が 10,000 から 30,000 の間にある場合にのみ、指定されたステートメントを出力に出力します。

コードは次のようになります。

if number >= 10000 and number <= 30000:
    print("you have to pay 5% taxes")
于 2020-01-11T11:34:02.353 に答える