初学者-改变基于数字的列表,输入不是str



我正试图在python中制作一个简单的井字游戏,但我目前被困在更改用于更改网格的列表:

grid = [" ", "1", "2", "3", "4", "5", "6", "7", "8", "9"]                       
def grids():                                                                   
print(grid[1] + " | " + grid[2] + " | " + grid[3])                        
print(grid[4] + " | " + grid[5] + " | " + grid[6])                                 
print(grid[7] + " | " + grid[8] + " | " + grid[9])                             
.....                                                                                 
# picked is what ive selected ( X or O )                                                                                              
while True:                                                                      
grids()                                                                           
choose = input(f"choose a number and place your {picked}:")               
if isinstance(choose, int) not in grid and choose not in grid:              
print("wrong input, try again")                                            
else:                                                                              
grid[choose] = grid[choose].replace(grid[choose], picked)              

(不能100%确定最后一部分是否正确,我在最后一个小时改变了很多,我甚至不知道它是否有效)

我以前让它工作,网格列表改变了我喜欢的方式。
但只有当我改变了input =..toint(input)=..

但是只要我输入一个字符串作为输入(比如"d"),它就崩溃了,不知道该怎么做。我也尝试了try/except功能,但没有任何运气。

如果您正在寻找查找输入类型的方法,那么您可以使用String.isnumeric

def until_user_enters_a_number():
clear = False
entered = 0
while not clear:
entered = input('I'm going no where before you enter a number: ');
clear = entered.isnumeric()
# make sure the number is between 0 and 9
# may be you also want to make sure the number wasn't selected once already
return int(entered)

这将使用户一直处于循环中,直到他输入一个有效的输入,您也可以在其中添加更多断言。

相关内容

  • 没有找到相关文章

最新更新