Я пытаюсь написать простой вопрос метода деления пополам, и он отлично работает, пока у меня нет определенного условного оператора, которое я прокомментировал. Что является причиной этого? Это не вопрос домашней работы.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 ...; если...; if ...; 'когда вы проверяете условия для одной и той же переменной. Он менее подвержен ошибкам и быстрее, потому что вы устраняете ненужные сравнения. – SvbZ3r0