所以我最近做了这段代码,它应该能猜出你脑子里想的数字。
from random import shuffle
def guess(start,limit):
nl = []
for i in range(start,limit+1):
nl.append(i)
shuffle(nl)
return nl[0]
def logic(start,limit):
p = False
while p == False:
j = guess(start,limit)
print 'Is your number %i?' % (j)
a = raw_input('Too High (h) or Too Low (l) or True (t)?\n')
if a.lower() == 'h':
limit = j - 1
elif a.lower() == 'l':
start = j + 1
elif a.lower() == 't':
p = True
return 'You\'re number was %i' % (j)
并且由于某种原因,即使在开始guess() 要求nl [0],有时当start 是54 并且limit 是56 时,Python 给了我这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 13, in logic
File "<stdin>", line 8, in guess
IndexError: list index out of range
为什么会发生这种情况,我该如何阻止它发生?