即使我要求[0],列表索引超出范围?

时间:2013-10-25 17:54:22

标签: python python-2.7

所以我最近制作了这段代码,并且它应该猜测你脑子里想的数字。

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)

由于某种原因,即使在一开始     猜测() 要求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

为什么会发生这种情况?如何阻止它发生?

2 个答案:

答案 0 :(得分:3)

你的清单是空的;如果limit低于start,则它会为空:

>>> from random import shuffle
>>> guess(1, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in guess
IndexError: list index out of range
>>> guess(1, 1)
1

因为然后生成的range()会产生一个空列表:

>>> range(1, 1)
[]

你需要在循环中测试它;如果玩家撒谎并表示猜测太高,虽然它确实正确或太低,那么最终limit可能低于start。< / p>

请注意,您只需使用random.choice()从序列中选择一个值,而不是random.shuffle()

import random

def guess(start,limit):
    return random.choice(range(start, limit + 1))

但如果它是范围内的值,只需使用random.randint()

def guess(start,limit):
    return random.randint(start, limit)

好的一点是,randint()包含了可供选择的值中的结束值,因此您不必在此使用limit + 1

稍微简化logic()功能,完全取消guess(),并为startlimit添加测试:

import random

def logic(start, limit):
    while True:
        guess = random.randint(start, limit)
        print 'Is your number %i?' % guess
        answer = raw_input('Too high (h), too low (l) or true (t)?\n')
        if answer.lower() == 'h':
            limit = guess - 1
            if limit < start:
                print "I give up, I've run out of options"
                return
        elif answer.lower() == 'l':
            start = guess + 1
            if start > limit:
                print "I give up, I've run out of options"
                return
        elif answer.lower() == 't':
            return 'Your number was %i' % guess

答案 1 :(得分:0)

如果您的nl数组为空,则不会得到nl [0]。