0

我在 python 中有一个很小的(愚蠢的)问题,我正在开发一个客户端-服务器程序以传输文本文件,目前我在尝试接收文件时遇到了一些困难。我的问题是当我问用户是否要保存文件时,即使他输入 Y 或 y 也不起作用,这是代码段:

print "Listening on input"
    a = 1
    while a == 1:
        pipe = open(fifoclient,'r')
        dr, dw, de = select.select([pipe], [], [], 0)
        if dr:
            content = pipe.read()
            liste = content.split("delimiter")
            expediteur = liste[1]
            filecont = liste[2]

            print "You received a file from : " + expediteur + ". Wanna save it?"
            answer = raw_input("O/N: ")
            while answer != "O" or answer != "N" or answer != "o" or answer != "n":
                print "Please enter a correct answer:\n"
                answer = raw_input("O/N: ")
            if answer == "O" or answer == "o":
                fileoutpath = str(raw_input("please enter the complete path for where you want to save the file to: "))
                while os.path.exists(fileoutpath):
                    print "THe file already exists, chose another path:\n"
                    fileoutpath = str(raw_input("please enter the complete path for where you want to save the file to: "))
                fileout = open(fileoutpath,'w')
                fileout.write(filecont)
                fileout.close()
            else:
                a = 0

问题是当它要求 O/N 时(Oui/Non 它是法语 :) )。即使我输入“o”或“O”,它仍然会告诉我输入正确的答案。任何帮助,将不胜感激。谢谢!

4

3 回答 3

2

这是一个布尔逻辑错误,你应该写:

while answer != "O" and answer != "N" and answer != "o" and answer != "n":

或者简单地说:

while answer not in "oOnN":
于 2012-04-27T17:14:41.123 回答
2

这是因为你的条件不对。

answer != "O" or answer != "N" or answer != "o" or answer != "n"

总是正确的。

它被评估为:

(answer != "O") or (answer != "N") or (answer != "o") or (answer != "n")

如您所见,其中一个语句始终为真,并且因为它们由 链接,所以无论您输入什么or,整个表达式的计算结果都是 。True

更改orand,它将按您的预期工作。

于 2012-04-27T17:12:49.970 回答
0

另一种考虑的方法

# ask question, suggest answer, convert response to lower case
answer = raw_input("Are you happy? (enter Y or N)").lower()

# allow several possible responses
if answer in ("y", "yes"):
    # do whatever for 'yes' response

您还可以反转测试:

if answer not in ("y", "yes"):
    # did not answer 'yes' (or equiv)
于 2012-04-27T17:28:13.260 回答