首页 > 解决方案 > 当我尝试接受用户输入时,我不断收到以下错误 - 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

标签: pythonpython-3.x

解决方案


如果用户没有输入有效的整数,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.")

推荐阅读