2016-06-17 5 views
2

私は簡単な二分法の質問を書こうとしていますが、私がコメントアウトした特定の条件文がない限り、それは完璧に機能します。これの理由は何ですか?これは宿題に関する質問ではありません。Python Bisection Number Guessing Game

low = 0 
high = 100 
ans = (low+high)/2 
print "Please think of a number between 0 and 100!" 
print "Is your secret number " + str(ans) + "?" 
response = 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. ") 
response = str(response) 
while response != "c": 
    if response == "h": 
     high = ans 
     ans = (low + high)/2 
     print "Is your secret number " + str(ans) + "?" 
     response = 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. ") 
     response = str(response) 

    if response == "l": 
     low = ans 
     ans = (low + high)/2 
     print "Is your secret number " + str(ans) + "?" 
     response = 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. ") 
     response = str(response) 

    if response == "c" : 
     break 

    # if response != "c" or response != "h" or response != "l": 
    #  response = raw_input("Please enter a 'h', 'l', or 'c' ") 
    # response = str(response) 

print "Game over. Your secret number was: " + str(ans) 

whileループはwhileループと同じ条件なので、これはですか?もしそうなら、これを変える最善の方法は何ですか?

+1

ちょうど先端。 'if ... elif ... else ...'の代わりに 'if ... elif ... else ...'を使ってください。もし...;もしあなたが同じ変数の条件をチェックしているならば...;バグが発生しにくく、不要な比較を排除することができます。 – SvbZ3r0

答えて

6

不等式を複数のものと比較しているため、その条件は常に真です。それはそれはlない場合は、はこのを行うhない場合は、この文字はcされていない場合、」尋ねるようなものだろう。それはそう、一度に三つのことはできませんあなたは、既存ので、それは常に真と評価されます。

を代わりに、あなたはあなたのケースでも、より良い上記の文章でまたはを持つとを交換する。など、基本的であるif response not in ['c','h','l']を使用する必要があり、ちょうどelseステートメントを使用します条件は既にあなたがチェックしようとしているものを保証します。

0

私はあなたがループしながら、ダブルを使用することをお勧め:

while True: 
    response = None 
    print "Is your secret number " + str(ans) + "?" 
    response = str(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.")) 

    while response not in ['h', 'c', 'l']: 
     response = str(raw_input("Please enter a 'h', 'l', or 'c' ")) 

    if response == 'c': 
     break 

    if response == 'l': 
     low = ans 
    else: 
     high = ans 
    ans = (low + high)/2