我最近决定重新审视我的TicTacToe游戏,该游戏是我大约3个月前制作的,需要重新调试,并且有一个特别的bug一直困扰着我。基本上,我有以下代码:
def player_choice(board):
'''Asks the player for their next position, calls a func to check if it's free'''
'''and returns the position if it's free for later use'''
spot = None
while spot not in range(1, 10) or not space_check(board, spot):
try:
spot = int(input("Choose your next position (1-9): "))
except:
print("Hmm, looks to me like your input was invalid")
else:
break
return spot
这是一个更大的方案中的函数,但使整个游戏中断的是我需要一个整数作为输入,严格来说,范围在1到10之间。在尝试错误处理之前,我使用了while循环,该循环不断询问是否提供了str:spot = int(input("Choose your next position (1-9): "))
while spot not in range (1, 10) or not space_check(board, spot):
spot = int(input("Looks like the spot you're trying to choose is invalid!\nPlease choose another position (1-9): "))
return spot
但是后来我切换到了这个版本,这里它不会接受str作为输入,但是会接受1-10范围之外的int值。我的问题是:我该怎么做才能按照我需要的方式工作,取一个严格介于1到10之间的整数并继续询问直到精确提供此输入?
最佳答案
四处移动,这似乎可行。虽然我不知道为什么else
总是被触发...
def player_choice2(board):
'''Asks the player for their next position, calls a func to check if it's free'''
'''and returns the position if it's free for later use'''
try:
spot = int(input("Choose your next position (1-9): "))
except:
print("Hmm, looks to me like your input was invalid")
spot = 0
while spot not in range(1, 10) or not space_check(board, spot):
try:
spot = int(input("Choose your next position ** (1-9) **: "))
except:
print("Hmm, looks to me like your input was invalid")
else:
# This always fires...?
print("Else....")
return spot
关于python - 在我得到特定范围内的整数之前,如何继续要求用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63271698/