我试图写一个简单的二分法方法问题,只要我没有一个我已经注释掉的某个条件语句,它就能完美地运行.这是什么原因?这不是一个家庭作业问题.
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)
Run Code Online (Sandbox Code Playgroud)
这是因为while循环与while循环具有相同的条件吗?如果是这样,改变这个的最佳方法是什么?
这种情况永远是真实的,因为你正在将不平等与多种事物进行比较.这就像问"如果这个角色不是c,或者它不是h,或者它不是l,那么这样做.它不能同时是三件事,所以总是会评价为真.
相反,你应该使用if response not in ['c','h','l'],这基本上是像更换或用和上面的句子.或者在您的情况下更好,只需使用一个else声明,因为您现有的条件已经确保您要检查的内容.