使用错误输入时,While循环值错误

时间:2020-07-08 23:38:04

标签: 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_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

1 个答案:

答案 0 :(得分:0)

您可以将输入环绕在............ .......... #if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION UnhandledException += (sender, e) => { if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break(); }; #endif 周围,以在将该值转换为整数之前测试该值是否为while loop

numeric or digit
相关问题