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

これは、あなたの条件が間違っているからです。

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

は常に真です。

次のように評価されます。

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

ご覧のとおり、ステートメントの 1 つが常に true であり、それらが によってチェーンされているため、入力内容に関係なく、or式全体が に評価されTrueます。

に変更orするとand、意図したとおりに機能します。

于 2012-04-27T17:12:49.970 に答える
2

これはブール論理エラーです。次のように記述してください。

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

または単に:

while answer not in "oOnN":
于 2012-04-27T17:14:41.123 に答える
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 に答える