如何在Python中限制用户输入为a-h加1-8格式的国际象棋棋盘坐标?
国际象棋坐标输入限制实现方案
你可以在原有黑白格判断逻辑前增加输入校验环节,避免非法输入导致程序报错,校验逻辑需覆盖3个核心规则:
- 输入长度必须为2位,规避输入过短/过长触发的索引异常
- 首字符必须为a-h区间的小写字母(如需兼容大写输入,可先统一转换为小写再校验)
- 第二位必须为1-8区间的数字
修改后的完整代码如下:
while True: square = input("Enter a chess square identifier : ").strip().lower() # 输入合法性校验 if len(square) != 2: print("输入不合法:请输入2位坐标,例:c4") continue if not ('a' <= square[0] <= 'h'): print("输入不合法:第一位需为a-h之间的字母") continue if not square[1].isdigit() or not (1 <= int(square[1]) <= 8): print("输入不合法:第二位需为1-8之间的数字") continue # 校验通过跳出循环 break # 原有黑白格判断逻辑 if ord(square[0]) % 2 != int(square[1]) % 2: print("white") else: print("black")
代码说明
- 用
while True循环实现输入不合法时自动要求重新输入,无需重启程序 - 增加
.lower()处理,用户输入A-H大写字母也可正常识别 - 每类非法输入都给出对应提示,方便用户调整输入
内容的提问来源于stack exchange,提问作者Nash Nash
相关产品推荐
相关产品推荐

