gpt4 book ai didi

python - 当我尝试接受用户输入时,我不断收到以下错误 - ValueError : invalid literal for int() with base 10: ''

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:29 25 4
gpt4 key购买 nike

我正在尝试创建一个井字游戏,用户在数字键盘上输入 1 - 9。当用户输入一个数字时,它会检查列表中相应的位置是否用空格(“”)表示,如果没有,则会用 X 替换列表中的该位置。

但是,当用户提供的输入只是按下 Enter 键时,我不断收到以下错误: 如果 update_board[int(user_input)] == "": ValueError:以 10 为基数的 int() 的文字无效:''

我提供了上下文代码的信息,但是如何检查用户输入是否只是按回车键?我试图检查 user_input == ""是否有效,但这也不起作用。我遇到了同样的错误。

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

最佳答案

如果用户没有输入有效的整数,int(user_input) 将引发此错误。这里的解决方案是提前检查 user_input 值或更简单地使用 try/except block

def get_int(msg):
while True:
user_input = input(msg).strip() # get rid of possible whitespaces
try:
return int(user_input)
except ValueError:
print("Sorry, '{}' is not a valid integer")


def player_turn():
while True:
user_input = get_int('Choose your position: ')
if update_board[user_input] == " ":
return user_input

print("That is not an option, please try again.")

关于python - 当我尝试接受用户输入时,我不断收到以下错误 - ValueError : invalid literal for int() with base 10: '' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53614797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com