这个问题在这里已有答案:
我正在尝试创建一个tic tac toe游戏,其中用户输入将在小键盘上为1 - 9 . 当用户输入一个数字时,它将检查列表中的相应位置是否用空格(“”)表示,如果没有,它将用X替换列表中的那个点 .
但是,当用户提供的输入只是他们按下回车键时,我一直收到以下错误:if update_board [int(user_input)] ==“”:ValueError:int(()with base 10的无效文字:''
I provided the info on the code for context, but how can I check if user input is them just hitting the enter key? I have attempted to check if user_input == "", but that doesn't work either. I get the same error.
update_board = ["#"," "," "," "," "," "," "," "," "," "]
def player_turn():
# Take in player's input so it can be added to the display board.
user_input = input('Choose your position: ')
if update_board[int(user_input)] == " ":
valid_input = True
else:
valid_input = False
while not valid_input:
user_input = input("That is not an option, please try again.\n> ")
if update_board[int(user_input)] == " ":
valid_input = True
else:
valid_input = False
return int(user_input)
player1 = "X"
update_board[(player_turn())] = player1
2 回答
如果用户未输入有效整数,
int(user_input)
将引发此错误 . 这里的解决方案是预先检查user_input
值,或者更简单地使用try / except块尝试在try except块中捕获用户输入
也许可以创建整个try ... else块的功能,这样你就不必再写两次了