首页 文章

当我尝试接受用户输入时,我不断收到以下错误 - ValueError:int(()with base 10的无效文字:''[duplicate]

提问于
浏览
1

这个问题在这里已有答案:

我正在尝试创建一个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 回答

  • 0

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

    尝试在try except块中捕获用户输入

    try:
        i = int(user_input)
    except:
        valid_input = False
        print('Please choose a number between 1 and 9')
    else:
        if update_board[int(user_input)] == " ":
            valid_input = True
        else:
            valid_input = False
    

    也许可以创建整个try ... else块的功能,这样你就不必再写两次了

相关问题