我寫了一些代碼來確定一個介於0和100之間的祕密數字。用戶告訴機器猜測的數字(這是該範圍的一半)也是高的低或恰到好處。基於輸入,機器使用平分搜索來調整猜測。當猜測正確時,用戶按下c鍵,遊戲結束。問題是,儘管「我不明白輸入」分支中存在條件,但當用戶按下c(一個有效條目)時,該分支會觸發,而這不是第一次猜測。Python:在簡單的二分搜索遊戲中意外的條件激活
例如,這裏是輸出 -
Please think of a number between 0 and 100!
Is your secret number 50?
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. l
Is your secret number 75?
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. c
Sorry, I did not understand your input.
Game over. Your secret number was:75
>>>
這裏是代碼 -
High=100
Low=0
Guess=50
user_input=0
print('Please think of a number between 0 and 100!')
while user_input != 'c':
print("Is your secret number"+" "+str(Guess)+"?")
userinput = 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.")
if user_input == 'h':
High=Guess
Guess= ((High+Low)/2)
if user_input == 'l':
Low=Guess
Guess= ((High+Low)/2)
if user_input != 'h' or 'l' or 'c':
print('Sorry, I did not understand your input.')
print ('Game over. Your secret number was:'''+ str(Guess))
在此先感謝。我已經在我的頭上幾個小時... ...
感謝您的條件信息。我接受了這份名單,因爲我們還沒有在課堂上接受他們,我把猜測的計算也作爲猜測本身。 – KGS