[英]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循環具有相同的條件嗎? 如果是這樣,改變這一狀況的最佳方法是什么?
該條件將永遠是正確的,因為您正在將不平等與多個事物進行比較。 這就像問“如果此字符不是c
, 還是不是h
, 還是不是l
, 請執行此操作 。一次不能是三件事,因此它將始終評估為true 。
相反,您應該if response not in ['c','h','l']
使用if response not in ['c','h','l']
,這基本上就像在上面的句子中替換or或 with 和 。 甚至對您而言更好,只需使用else
語句,因為您的現有條件已經可以確保您嘗試檢查的內容。
我建議您使用double while循環:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.