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

Python 当使用不正确的输入时,While循环值错误,python,while-loop,user-input,Python,While Loop,User Input,我正在尝试创建一个基本的游戏,这个游戏的一个阶段是用户输入1-9的值。如果用户输入这些值中的一个,游戏就会运行,但是如果他们在到达字段时简单地按回车/回车键,我就会得到一个值错误。以下是错误: <ipython-input-6-061a946b3a03> in <module> ----> 1 ttt_game() <ipython-input-5-b42c27ce7032> in ttt_game() 36 while game_o

我正在尝试创建一个基本的游戏,这个游戏的一个阶段是用户输入1-9的值。如果用户输入这些值中的一个,游戏就会运行,但是如果他们在到达字段时简单地按回车/回车键,我就会得到一个值错误。以下是错误:

<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:

    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

不幸的是,我也不能让这个解决方案起作用。如示例所示,当直接应用时,python在命中while循环时会抛出一个错误,甚至不需要玩家的输入。当我尝试修复for循环的其余部分的缩进等,并为单个while循环添加一个中断时,python抛出了一个unboundlocalerror,因为player_guess在赋值之前被引用了。@brandonvington您得到了什么错误,我已经删除了
>0和<9
的条件,因为现在错误是由
>0导致的,这最终起作用,我感谢您的帮助!
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