【发布时间】:2020-08-05 18:48:07
【问题描述】:
我最近决定重新审视我大约 3 个月前制作的井字游戏,并以全新的眼光进行调试,特别是这个错误一直困扰着我。基本上,我有这个代码:
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,它会不断要求一个 int:
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 之间的整数并继续询问直到准确地提供此输入?
【问题讨论】:
标签: python python-3.x function error-handling while-loop