2 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
這是一個(gè)使用的版本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')
當(dāng)它遇到 a 時(shí)ValueError,它會(huì)認(rèn)為它找到了您的號(hào)碼。請(qǐng)確保沒有其他情況可能導(dǎo)致此代碼給出錯(cuò)誤答案,因?yàn)槲绎@然還沒有對(duì)其進(jìn)行徹底測(cè)試。
您還可以將這些try/except子句放在 a 中def以使其更加緊湊,因?yàn)樗鼈兪窍嗤拇a片段,但我不確定您的項(xiàng)目是否允許這樣做,所以我保留了它。

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
你在numberHasBeenGuessed = Truewhile 循環(huán)之外 - 這意味著在循環(huán)結(jié)束之前它不能被調(diào)用 - 所以它將永遠(yuǎn)卡住。
當(dāng)它達(dá)到你的猜測(cè)時(shí) - 假設(shè)我有數(shù)字 7。你的程序會(huì)詢問(wèn)“7 比 7 小還是大?” 顯然這是沒有意義的,7就是7。7 不小于也不大于 7:你的程序知道這一點(diǎn)并崩潰。所以你需要引入一個(gè)新的用戶輸入選項(xiàng):
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)在,當(dāng)您的數(shù)字被猜到時(shí),您可以輸入“就是這樣”,程序就會(huì)以您想要的輸出結(jié)束。(當(dāng)然,將輸入和內(nèi)容更改為您想要的)
最后的程序員提示:用主題標(biāo)簽評(píng)論你的代碼,這樣你就知道(以及其他人的幫助)每個(gè)部分的作用。
添加回答
舉報(bào)