当使用不正确的输入时,While 循环值错误

While Loop Value Error when incorrect input used

我正在尝试创建一个基本游戏,该游戏的一个阶段是用户输入 1-9 之间的值。如果用户输入其中一个值,游戏就会运行,但如果他们在到达该字段时只是简单地点击 return/enter,我会收到一个值错误。以下是错误:

<ipython-input-6-061a946b3a03> in <module>
----> 1 ttt_game()

<ipython-input-5-b42c27ce7032> in ttt_game()
     36     while game_on == True:
     37         while choose_first == 0:
---> 38             player_guess = int(input('Choose a space 1-9: '))
     39             for position in board:
     40                 if position in board[player_guess] == ' ':

ValueError: invalid literal for int() with base 10: ''

我正在尝试弄清楚如何使输入调用被再次询问,或者让 while 循环重新启动并打印一条消息,如“输入无效,再试一次”

这里是原始代码块,如果有帮助的话。

 while game_on == True:
        while choose_first == 0:
            player_guess = int(input('Choose a space 1-9: '))
            for position in board:
                if position in board[player_guess] == ' ':
                    board[player_guess] = 'X'
                    display_board(board)
                    if win_check(board,'x') == False:
                        pass
                    else:
                        display_board(board)
                        print('Player 1 has won the game!')
                        break
                    
                elif board[player_guess] == 'O':
                    print ('Space already chosen, choose another.')
                    pass
                else:
                    choose_first = 1
                    pass

您可以将输入包裹在 while loop 周围,以测试该值是否为 numeric or digit,然后再将其转换为整数。

while game_on == True:
while choose_first == 0:

    result = ""
    while(not result.isdigit()): 
        # you can also use result.isnumeric()
        result = input('Choose a space 1-9: ')

    player_guess = int(result)
    for position in board:
        if position in board[player_guess] == ' ':
            board[player_guess] = 'X'
            display_board(board)
            if win_check(board, 'x') == False:
                pass
            else:
                display_board(board)
                print('Player 1 has won the game!')
                break

        elif board[player_guess] == 'O':
            print('Space already chosen, choose another.')
            pass
        else:
            choose_first = 1
            pass