简体   繁体   中英

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?

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.

I suggest you use a double while loop :

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM