[英]How to fix a 'list index out of range' error?
一旦第二次输入“较高”,此代码将给我一个“索引超出范围”错误。 救命?!
import random
print("Think of a number from 1 to 100")
nums = list(range(0, 101))
correct = 0
counter = 0
while correct == 0:
counter += 1
guess = nums[int(len(nums) / 2)]
higher_lower = input("Is this your number: " + str(guess) + "? If not,
is your number higher or lower or than " + str(guess) + "?: ")
if higher_lower == "higher":
nums = nums[guess:]
print(nums)
elif higher_lower == "lower":
nums = nums[:guess]
print(nums)
elif higher_lower == "yes":
correct = 1
print("I have guessed your number " + str(guess) + " in " + str(counter) +
" guesses")
应该通过询问用户的电话号码是高于还是低于当前的猜测值来猜测用户的号码。
在您的代码中, guess
显然是当前正在猜测的数字,但是在nums=nums[:guess]
,您也可以将其用作索引。 只要只删除末尾的值,就可以了,但是,一旦从开头删除内容,所有内容就会向后移动,可能(?)超出范围。
.index()
获取索引 guess
作为索引,这意味着将其设置为len(nums)//2
并在文本中使用nums[guess]
(lower_than - higher_than) // 2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.