[英]check for variable in 2d list in python
I'm trying to get the user to input a number from 1 to 9. The code is supposed to check if the number is in the list "board" or already taken.我试图让用户输入一个从 1 到 9 的数字。代码应该检查该数字是否在列表“板”中或已经被使用。 If it's not taken the number is turned into "O".
如果不取,则数字变为“O”。 If the number is not in the list or already taken the loop is supposed to re-ask the user for input.
如果该号码不在列表中或已被占用,则循环应该重新要求用户输入。 However, even if the number is in the list and not taken, the function asks the user for input twice.
然而,即使数字在列表中并且未被采用,该函数也会要求用户输入两次。 If I move the else statement on line with the if statement, I get an infinite loop asking for input.
如果我将 else 语句与 if 语句一起移动,我会得到一个无限循环,要求输入。
Here's the code:这是代码:
# ask the unser to make a move
def userMove():
move = int(input("Please make your move: "))
check = True
# check if move is already taken
while check:
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == move:
board[i][j] = "O"
check = False
else:
print("This field is either already taken or not on the board")
move = int(input("Please choose another move: "))
您可以使用any()
检查值是否在二维列表中:
if any(move in sublist for sublist in board):
Your problem is caused by the else clause being executed always.您的问题是由始终执行的 else 子句引起的。 The posted code can be fixed as follows.
发布的代码可以修复如下。
Revised Code修订代码
# ask the unser to make a move
def userMove():
move = int(input("Please make your move: "))
check = True
# check if move is already taken
while check:
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == move:
board[i][j] = "O"
check = False
break
if not check:
break
else:
# only executes if break not encountered in for i loop
print("This field is either already taken or not on the board")
move = int(input("Please choose another move: "))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.