一旦第二次输入“更高”,此代码会给我一个“索引超出范围”错误。帮助吗?!
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")
应该通过询问用户的号码是高于还是低于当前的猜测来猜测用户的号码。
答案 0 :(得分:0)
在您的代码中,guess
显然是当前正在猜测的数字,但是在nums=nums[:guess]
中,您也将其用作索引。只要只删除末尾的值,就可以了,但是,只要从开头删除内容,一切都会向后移动,可能(?)超出范围。
.index()
获取索引guess
作为索引,这意味着将其设置为len(nums)//2
并在文本中使用nums[guess]
(lower_than - higher_than) // 2
。