我知道在这个例子中我的索引不能大于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'
对于任何大于9的
xInput
,您仍然被困在while
循环中,因为xInput > 9
是循环中的条件之一。你知道吗触发索引器的代码行:
永远联系不到
您正在使用
or
条件进行求值。你知道吗当其中任何一个条件为真时,其余的条件都不会被计算。你知道吗
如果需要更严格地控制,可以尝试使用
and
或xor
条件输入10(所以
xInput = 9
)抛出异常的原因是board
列表的长度只有9。在while
循环中,如果xInput == 9
,它将退出,因为只有当xInput
小于9时,它才被设置为循环。你知道吗因此,如果
xInput
是9,那么它会尝试计算board[9]
,因为列表的索引从0开始,而不是从1开始。因此您首先提到的while循环是正确的,因为这里有循环条件
xInput <= 9
,而不是xInput < 9
,所以它只会在xInput == 8
时退出循环,这将正确计算。你知道吗相关问题 更多 >
编程相关推荐