我正在尝试创建一个基本游戏,这个游戏的一个阶段是用户输入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
在将值转换为整数之前,可以将输入封装在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