2 回答

TA貢獻1827條經(jīng)驗 獲得超8個贊
這是一個使用的版本try/except
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y', 'n', or 'Thats it'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
try:
randomNumber = random.randint(lowBound,highBound)
except ValueError:
numberHasBeenGuessed = True
elif response == "y" or response == "Y":
highBound = randomNumber - 1
try:
randomNumber = random.randint(lowBound,highBound)
except ValueError:
numberHasBeenGuessed = True
else:
print ('Please only type y, Y, n or N as responses')
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
當它遇到 a 時ValueError,它會認為它找到了您的號碼。請確保沒有其他情況可能導致此代碼給出錯誤答案,因為我顯然還沒有對其進行徹底測試。
您還可以將這些try/except子句放在 a 中def以使其更加緊湊,因為它們是相同的代碼片段,但我不確定您的項目是否允許這樣做,所以我保留了它。

TA貢獻1820條經(jīng)驗 獲得超10個贊
你在numberHasBeenGuessed = Truewhile 循環(huán)之外 - 這意味著在循環(huán)結束之前它不能被調(diào)用 - 所以它將永遠卡住。
當它達到你的猜測時 - 假設我有數(shù)字 7。你的程序會詢問“7 比 7 小還是大?” 顯然這是沒有意義的,7就是7。7 不小于也不大于 7:你的程序知道這一點并崩潰。所以你需要引入一個新的用戶輸入選項:
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y', 'n', or 'Thats it'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
print(randomNumber)
elif response == "y" or response == "Y":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
print(randomNumber)
elif response == "Thats it": #New input option 'Thats it'
numberHasBeenGuessed = True #Stops the while loop
else:
print ('Please only type y, Y, n or N as responses')
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
現(xiàn)在,當您的數(shù)字被猜到時,您可以輸入“就是這樣”,程序就會以您想要的輸出結束。(當然,將輸入和內(nèi)容更改為您想要的)
最后的程序員提示:用主題標簽評論你的代碼,這樣你就知道(以及其他人的幫助)每個部分的作用。
添加回答
舉報