web-dev-qa-db-ja.com

Pythonトラブルの「または」条件付き

Pythonを学習していますが、少し問題があります。私が取っているコースで似たようなものを見て、この短いスクリプトを思いついた。以前は「or」と「if」を使用して成功していました(ここではあまり表示されません)。何らかの理由で、これを機能させることができないようです:

test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()

if x == "monkey" or "monkeys":
    print "You're right, they are awesome!!"
Elif x != "monkey" or "monkeys":
    print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right animal."

しかし、これはうまくいきます:

test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()

if x == "monkey":
    print "You're right, they are awesome!!"
Elif x != "monkey":
    print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right animal."

おそらく、または条件がここに収まりません。しかし、私は試しました、など。私はこれがサルを受け入れるようにする方法が大好きで、他のすべてがElifをトリガーします。

7
Interrupt

ほとんどのプログラミング言語のブール式は、英語と同じ文法規則に従っていません。各文字列を個別に比較し、それらをorで接続する必要があります。

if x == "monkey" or x == "monkeys":
    print "You're right, they are awesome!!"
else:
    print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right animal."

間違ったケースのテストを行う必要はありません。elseを使用してください。しかし、そうした場合は、次のようになります。

Elif x != "monkey" and x != "monkeys"

論理クラスで deMorganの法則 について学んだことを覚えていますか?彼らは、接続詞または選言を逆にする方法を説明します。

22
Barmar

gkaylingは正しいです。最初のifステートメントは、次の場合にtrueを返します。

x == "サル"

または

「サル」はtrueと評価されます(null文字列ではないため、評価されます)。

Xがいくつかの値の1つであるかどうかをテストする場合、「in」演算子を使用すると便利です。

test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()

if x in ["monkey","monkeys"]:
    print "You're right, they are awesome!!"
else:
    print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right
4
Rob Falck

if x == "monkey" or x == "monkeys":

3
gkayling