python - 当我尝试接受用户输入时,我不断收到以下错误 - ValueError: invalid literal for int() with base 10: ''
问题描述
我正在尝试创建一个井字游戏,其中用户输入将是小键盘上的 1 - 9。当用户输入一个数字时,它会检查列表中的对应点是否用空格(“”)表示,如果没有,它将用 X 替换列表中的那个点。
但是,当用户提供的输入只是他们按回车键时,我不断收到以下错误: if update_board[int(user_input)] == " ": ValueError: invalid literal for int() with base 10: ''
我提供了有关上下文代码的信息,但我如何检查用户输入是否只是按回车键?我试图检查 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 块
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.")
推荐阅读
- twilio - Twilio 语音访问令牌到期时间
- flutter - 我可以在应用程序终止时在后台运行代码吗?
- html - 如何在 CSS Grid 项目周围设置内部边框?
- angular - Gitlab CI/CD - 如何知道进程何时完成
- javascript - 可以同时使用firebase和express吗?
- css - 单击时css更改占位符(无js)
- c++ - 添加 _AFXDLL 宏和 clr 支持后找不到 InterlockedAdd64
- symfony - Symfony 5 无效的防火墙“api”:找不到用户提供程序“app_user_provider”
- javascript - render.js 中的电子属性无法访问
- vue.js - Vue保护路径免受编辑的本地存储