I have a code like this:
if (X or Y) == ("Cat" or "Dog" or "Fish" or "Bird"):
print X, Y
It is only working if X == "Cat". Does anyone know my mistake here?
I have a code like this:
if (X or Y) == ("Cat" or "Dog" or "Fish" or "Bird"):
print X, Y
It is only working if X == "Cat". Does anyone know my mistake here?
私はあなたがこのような論理が欲しいと思います:
animals = ["Cat", "Dog", "Fish", "Bird"]
if X in animals or Y in animals:
print X, Y
あなたのコードでは、式( "Cat"、 "Dog"、 "Fish"、 "Bird")は、あなたが望まないと確信している論理式として扱われます。たまたま、この表現は「猫」と評価され、観察された行動を説明します。
>>> 'cat' or 'dog'
'cat'
>>> 'cat' and 'dog'
'dog'
これらは文字列に対する論理演算です。空でない文字列はTrue値と見なされます。空の文字列はFalseと見なされます。Pythonの論理演算子は、オペランドと同じ型の値を返します(両方のオペランドが同じ型であると想定しています)。短絡評価は、ここでの動作を説明しorますand。
いずれにせよ、文字列に対して論理演算を実行することはほとんど意味がありません。
Pythonの演算子は、 「trucy」orの場合は最初の引数を返し、それ以外の場合は2番目の引数を返します。比較の右側は常にと評価され、左側は「trucy」である限り評価されます。"Cat"XX
探しているロジックを取得するための最も簡潔な方法は次のとおりです。
if set((X, Y)) & set(("Cat", "Dog", "Fish", "Bird")):
# whatever
何が起こるかというと、あなたは運動しているX or YだけXです。それから、あなたはそれが0でないので、Cat or Dog or..あなたにちょうど与えることで、働いています。Cat
あなたが欲しいものは:
if X in ("Cat","Dog", "Fish", "Bird") or Y in ("Cat","Dog", "Fish", "Bird"):
#taa daa!
Your problem is in the way Python evaluates or. If a is truthy (not-zero, or a non-empty string, or an object) a or b returns a; otherwise it returns b. So "string" or b will always evaluate to "string".
So "Cat" or "Dog" or "Fish" or "Bird" will always evaluate to "Cat",
and X or Y will always evaluate to X (so long as X is a string of one or more characters)
and X=="Cat" is obviously only true when X is "Cat".
animals = set(["Cat","Dog","Fish","Bird"])
if X in animals or Y in animals:
print X, Y