1
Another_Mark = raw_input("would you like to enter another mark? (y/n)")

while Another_Mark.lower() != "n" or Another_Mark.lower() != "y":
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")

if Another_Mark == "y":
    print "blah"

if Another_Mark == "n":
    print "Blue"

これは、最初の 3 行を除いて、私が使用している実際のコードではありません。とにかく、私の質問は、値「y」または「n」を入力しても、3 行目に別のマークを入力するかどうかを再度尋ねられたときに、なぜ while ループが繰り返されるのかということです。無限に繰り返されるループにはまっています。Another_Mark の値が「y」または「n」に変更された場合は、繰り返されません。

4

4 に答える 4

5

試す:

while Another_Mark.lower() not in 'yn':
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")

not in演算子は、指定されたオブジェクトが指定された iterable で見つからない場合は true を返し、それ以外の場合は false を返します。だから、これはあなたが探しているソリューションです:)


これは、根本的にブール代数エラーのために機能していませんでした。ラティウェアが書いたように:

not (a or b) (あなたが説明するもの) は、not a or not b (あなたのコードが言うこと) と同じではありません

>>> for a, b in itertools.product([True, False], repeat=2):
...     print(a, b, not (a or b), not a or not b, sep="\t")
... 
True    True    False   False
True    False   False   True
False   True    False   True
False   False   True    True
于 2013-04-14T18:11:31.443 に答える
3

入力が「n」の場合、それは「y」ではないため、真です。逆に「y」なら「n」ではありません。

これを試して:

while not (Another_Mark.lower() == "n" or Another_Mark.lower() == "y"):
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
于 2013-04-14T18:12:05.233 に答える
1

ループの背後にあるロジックが間違っています。これはうまくいくはずです:

while Another_Mark.lower() != "n" and Another_Mark.lower() != "y":
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
于 2013-04-14T18:14:25.197 に答える
1

OR の代わりに AND を使用する必要があります。

これは、ブール論理が分散する方法です。あなたは言うことができます:

NOT ("yes" OR "no")

または、OR を AND に反転することで、NOT を括弧に分配することができます (これがあなたがやろうとしていることです)。

(NOT "yes") AND (NOT "no")
于 2013-04-14T18:16:14.970 に答える