Python猜测游戏:索引器:范围对象索引超出范围
我创建了一个游戏,在这个游戏中,我从1到100中选择一个数字,然后电脑猜出来。然而,当我选择6以下的数字时,我会得到索引器。为什么会这样 这是我的密码:Python猜测游戏:索引器:范围对象索引超出范围,python,python-3.x,index-error,Python,Python 3.x,Index Error,我创建了一个游戏,在这个游戏中,我从1到100中选择一个数字,然后电脑猜出来。然而,当我选择6以下的数字时,我会得到索引器。为什么会这样 这是我的密码: 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[i
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))
换乘线路
list_nums = list_nums[1: int(len(list_nums)/2)]
致:
因为,列表索引从零开始
或:
因为,Python知道列表从零开始。我检查了您的代码并在我的系统上运行。每次列表大小减小,最后变为0时。当代码计算行mid_元素=list_nums[intlenlist_nums/2-1]时,答案是-1,超出范围 我已经跟踪了代码,输出如下: Hello用户,在你的脑海中选择一个1-100之间的数字,我会试着猜出来。。。 列表长度_num:100 你选的号码是50吗 是太高还是太低太高 列表长度_num:49 你选的号码是25吗 是太高还是太低太高 列表长度_num:23 你选的号码是13吗 是太高还是太低太高 列表长度_num:10 你选的是8号吗 是太高还是太低太高 列表长度\u num:4 你选的是6号吗 是太高还是太低太高 列表的长度\u num:1 你选的是6号吗 是太高还是太低太高 无效项..请重试 列表的长度\u num:0
因此,请对上述答案进行修改。非常感谢。。它起作用了。这只是我编写代码的第二周。这似乎是个愚蠢的错误。
list_nums = list_nums[0: int(len(list_nums)/2)]
list_nums = list_nums[: int(len(list_nums)/2)]