2 回答
TA贡献1827条经验 获得超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条经验 获得超10个赞
你在numberHasBeenGuessed = Truewhile 循环之外 - 这意味着在循环结束之前它不能被调用 - 所以它将永远卡住。
当它达到你的猜测时 - 假设我有数字 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')
现在,当您的数字被猜到时,您可以输入“就是这样”,程序就会以您想要的输出结束。(当然,将输入和内容更改为您想要的)
最后的程序员提示:用主题标签评论你的代码,这样你就知道(以及其他人的帮助)每个部分的作用。
添加回答
举报