私は簡単な二分法の質問を書こうとしていますが、私がコメントアウトした特定の条件文がない限り、それは完璧に機能します。これの理由は何ですか?これは宿題に関する質問ではありません。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ループと同じ条件なので、これはですか?もしそうなら、これを変える最善の方法は何ですか?
ちょうど先端。 'if ... elif ... else ...'の代わりに 'if ... elif ... else ...'を使ってください。もし...;もしあなたが同じ変数の条件をチェックしているならば...;バグが発生しにくく、不要な比較を排除することができます。 – SvbZ3r0