为什么“列表索引超出范围”错误只在输入10时出现?

2024-04-19 15:06:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道在这个例子中我的索引不能大于8,所以输入10(因此xInput等于9)会导致列表索引超出范围。但任何大于10的数字似乎都能很好地工作。你知道吗

我试过了

while xInput < 0 or xInput >= 9 or 'o' == board[xInput] or 'x' == board[xInput]:

它确实工作正常。但我似乎不明白为什么我的另一个不行

这是我的原始代码

board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
xInput = 90
oInput = 90
while xInput < 0 or xInput > 9 or 'o' == board[xInput] or 'x'==board[xInput]:
        xInput = int(input("x: ")) - 1
board[xInput] = 'x'

Tags: or代码board列表input数字例子int
3条回答

对于任何大于9的xInput,您仍然被困在while循环中,因为xInput > 9是循环中的条件之一。你知道吗

触发索引器的代码行:

board[xInput] = 'x'

永远联系不到

您正在使用or条件进行求值。你知道吗

当其中任何一个条件为真时,其余的条件都不会被计算。你知道吗

example: A or B or C, where A/B/C could be some expression.

The boolean value of this depends on whether any of A/B/C is true. 

如果需要更严格地控制,可以尝试使用andxor条件

输入10(所以xInput = 9)抛出异常的原因是board列表的长度只有9。在while循环中,如果xInput == 9,它将退出,因为只有当xInput小于9时,它才被设置为循环。你知道吗

因此,如果xInput是9,那么它会尝试计算board[9],因为列表的索引从0开始,而不是从1开始。因此

board[0] == 1
board[1] == 2
...
board[8] == 9
board[9] == ???

您首先提到的while循环是正确的,因为这里有循环条件xInput <= 9,而不是xInput < 9,所以它只会在xInput == 8时退出循环,这将正确计算。你知道吗

相关问题 更多 >