Adam Warner Adam Warner - 5 months ago 11
Python Question

Python Bisection Number Guessing Game

I am trying to write a simple bisection method question and it works perfectly fine as long as I don't have a certain conditional statement which I have commented out. What is the reason for this? This is not a homework question.

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)


Is this because the while loop has the same condition as the while loop? If so what is the best way to change this?

Answer

That condition will always be true because you are comparing for inequality with multiple things. It would be like asking "If this character isn't c, or if it isn't h, or if it isn't l, do this. It can't be three things at once, so it will always evaluate as true.

Instead, you should use if response not in ['c','h','l'], which is basically like replacing or with and in the sentence above. Or even better in your case, just use an else statement because your existing conditions already ensure what you are trying to check for.