所以,最近我一直在尝试编写一个反向猜数游戏,让计算机尝试猜测我想到的数字。我应该得到的输出如下所示:
Enter the range: 6
Think of a random number between 1 and 6 and press enter once done!
Is it smaller than 4, 'y' or 'n'?y
Is it smaller than 2, 'y' or 'n'?n
Is it smaller than 3, 'y' or 'n'?y
Wonderful it took me 3 questions to find out that you had the number 2 in mind!
到目前为止,这些是我的代码:
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' or 'n'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
elif response == "y" or response == "Y":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
else:
print ('Please only type y, Y, n or N as responses')
numberHasBeenGuessed = True
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
主要算法正在工作,但不知怎的,当数字被“猜测”时它无法检测到它......有人知道为什么吗?
我将非常感谢您的帮助:)
斯蒂芬大帝
拉莫斯之舞
相关分类