在python中"OR"的missbehaviour

Hyo*_*ipo 0 python canopy

Hy ...我只是在学习python.我做了一个这样的程序:

guess = raw_input("please input something...");
while (guess != 'h'):
    guess = raw_input("pleae input something again....");
    print(guess);

print("Thanks...");
Run Code Online (Sandbox Code Playgroud)

嗯......上面的程序运行良好.但是当我在猜测后输入"OR"时!='h'就像这样:

guess = raw_input("please input something...");
while (guess != 'h') or (guess != 't'):
    guess = raw_input("pleae input something again....");
    print(guess);

print("Thanks...");
Run Code Online (Sandbox Code Playgroud)

以上程序在while循环中永远运行.那里发生了什么?我认为在输入h或t后循环将结束

Reu*_*ani 9

你的情况总是如此:

(guess != 'h') or (guess != 't')
Run Code Online (Sandbox Code Playgroud)

总是如此(如果一部分不是真的,则意味着另一部分是).

如果你在这里使用De-Morgan定律你会得到一些更明显的东西:

not (guess == 'n' and guess == 't')
Run Code Online (Sandbox Code Playgroud)

这显然真的(guess只能是一件事).

你可能想要:

(guess != 'h') and (guess != 't')
Run Code Online (Sandbox Code Playgroud)

或者更好的是:

while guess not in 'ht':
Run Code Online (Sandbox Code Playgroud)


omu*_*gru 5

while (guess != 'h') or (guess != 't') 
Run Code Online (Sandbox Code Playgroud)

这条线基本上说:如果我的输入不是'h'或我的输入不是't',则重复循环.由于控制台输入不能同时为'h'和't',因此循环将永远重复.你确定你不是在寻找while guess != 'h' and guess != 't'或者while not (guess == 'h' or guess == 't')(从逻辑的角度看它们都是相同的)吗?