Python猜谜游戏:IndexError:范围对象索引超出范围

时间:2018-10-06 15:21:44

标签: python python-3.x index-error

我创建了一个游戏,其中我选择一个从1到100的数字,然后计算机会猜出它。但是,当我选择低于6的数字时会出现IndexError。为什么会发生这种情况?。

这是我的代码:

print("Helllo user, select a number from 1-100 in your mind and i will try to guess it...")

list_nums = range(1,101)
counter = 0

while True :
    mid_element = list_nums[int(len(list_nums)/2)-1]
    print(" Is your selected number {}".format(mid_element))
    counter = counter + 1
    response = str(input("is it too high or too low..? : "))
    try:
        if response == "too low":
            list_nums = list_nums[int(len(list_nums)/2):int(len(list_nums))]
            mid_element = list_nums[int(len(list_nums)/2)]

        elif response == "too high":
            list_nums = list_nums[1:int(len(list_nums)/2)]
            mid_element = list_nums[int(len(list_nums)/2)]

        elif response == "correct":
            print("Perfect i finally guessed it. Your number is {}\n".format(mid_element))
            break
    except:
        print("Invalid entry..Try again")
        continue

print("\nI guessed it in {} attempts".format(counter))

2 个答案:

答案 0 :(得分:1)

换行

list_nums = list_nums[1: int(len(list_nums)/2)]

收件人:

list_nums = list_nums[0: int(len(list_nums)/2)]

因为列表索引从零开始。

或者:

list_nums = list_nums[: int(len(list_nums)/2)]

因为,Python知道列表从零开始。

答案 1 :(得分:0)

我遍历了您的代码并在我的系统上运行。每次您的列表大小减小时,最终它都变为0。这时,当您的代码计算行mid_element = list_nums[int(len(list_nums)/2)-1]时,答案是-1,这超出范围。

我已经跟踪了代码,输出如下:

Helllo user, select a number from 1-100 in your mind and i will try to guess it... Length of list_num: 100 Is your selected number 50 is it too high or too low..? : too high Length of list_num: 49 Is your selected number 25 is it too high or too low..? : too high Length of list_num: 23 Is your selected number 13 is it too high or too low..? : too high Length of list_num: 10 Is your selected number 8 is it too high or too low..? : too high Length of list_num: 4 Is your selected number 6 is it too high or too low..? : too high Length of list_num: 1 Is your selected number 6 is it too high or too low..? : too high Invalid entry..Try again Length of list_num: 0

进行上述答案中给出的更改。