Python井字棋程序中while循环内in运算符判定失效问题
问题原因
核心问题是类型不匹配:
- Python中
input()函数的返回值默认是字符串(str)类型,你从输入拿到的num是类似"3"的字符串,而gone列表中存储的是已经落子位置的整数(int)类型值,比如3。不同类型的值在in判定时会被视为不相等,所以"3" in [3]的结果是False,直接导致判定失效。 - 你测试
not num in gone得到相反效果也可以佐证这一点:因为num in gone本身就一直返回False,取反后变成True,自然会触发相反的判定逻辑。
修复方案
根据你的存储习惯可以二选一处理:
- 统一使用整数类型做判定和存储
gone = [] turn = 0 def play(XO,player): while True: num = input("\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ") # 合法数字转int后再做存在性判定 while (not num.isdigit()) or (not (1 <= int(num) <= 9)) or (int(num) in gone): num = input("\nValue was not an available number.\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ") # 后续存入gone的也是int类型 num = int(num) gone.append(num) # 剩余落子逻辑
- 统一使用字符串类型做判定和存储
gone = [] turn = 0 def play(XO,player): while True: num = input("\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ") # 直接用字符串做存在性判定 while (not num.isdigit()) or (not (1 <= int(num) <= 9)) or (num in gone): num = input("\nValue was not an available number.\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ") # 后续存入gone的是原始字符串类型 gone.append(num) # 剩余落子逻辑
内容的提问来源于stack exchange,提问作者LeftHandedPsycho
相关产品推荐
相关产品推荐

