0

0 から 100 までの秘密の数字を決定するコードを書きました。ユーザーは、推測した数字 (範囲の半分) が高すぎるか、低すぎるか、またはちょうどよいかをマシンに伝えます。入力に基づいて、マシンは二分探索を使用して推測を調整しました。推測が正しい場合、ユーザーは c を押してゲームを終了します。問題は、「入力を理解できませんでした」ブランチに配置された条件にもかかわらず、ユーザーが c (有効なエントリ) を押したときにこのブランチがトリガーされ、それが最初の推測ではないことです。

たとえば、ここに出力があります-

Please think of a number between 0 and 100!
Is your secret number 50?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 75?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
Sorry, I did not understand your input.
Game over. Your secret number was:75
>>> 

そして、ここにコードがあります-

    High=100
    Low=0
    Guess=50
    user_input=0

    print('Please think of a number between 0 and 100!')

    while user_input != 'c':
        print("Is your secret number"+" "+str(Guess)+"?")
        userinput = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
        if user_input == 'h':
            High=Guess
            Guess= ((High+Low)/2)
        if user_input == 'l':
            Low=Guess
            Guess= ((High+Low)/2)
        if user_input != 'h' or 'l' or 'c':
            print('Sorry, I did not understand your input.')

    print ('Game over. Your secret number was:'''+ str(Guess))

前もって感謝します。私はこれについて何時間も頭を悩ませてきました....

4

3 に答える 3

1

その条件の代わりにこれを試してください。

if user_input not in ['h','l','c']:
      print('Sorry, I did not understand your input.')

かどうかを確認する必要user_inputはおそらくないでしょう。hlif

    if user_input == 'h':
        High=Guess
        Guess= ((High-Low)/2)
    elif user_input == 'l':
        Low=Guess
        Guess= ((High-Low)/2)
    elif user_input == 'c':
        pass # the while statement will deal with it or you could break
    else:
        print('Sorry, I did not understand your input.')
于 2013-11-26T21:53:42.617 に答える
0

条件はそのようには機能しません。次のようなものが必要です:

# Check each condition explicitly
if user_input != 'h' and user_input != 'l' and user_input != 'c':

または:

# Check if the input is one of the elements in the given list
if user_input not in ["h", "c", "l"]:

あなたの現在のアプローチは次のように理解されています

if (user_input != 'h') or ('l') or ('c'):

そしてlandctrueであるため、そのブランチは常に実行されます。


の使用を検討することもelifできるため、条件は次のようになります。

while True:
    if user_input == 'h':
        High=Guess
        Guess= ((High-Low)/2)
    elif user_input == 'l':
        Low=Guess
        Guess= ((High-Low)/2)
    elif user_input == "c":
        # We're done guessing. Awesome.
        break
    else:
        print('Sorry, I did not understand your input.')
于 2013-11-26T21:52:42.743 に答える