python - Python List 无法将变量识别为整数
问题描述
该代码适用于使用 Randint 和列表的井字游戏。有人可以解释为什么会出现错误吗?我试图将其更改为整数和字符串,但它仍然不起作用。
import random
boardt = [1, 2, 3]
boardm = [4, 5, 6]
boardd = [7, 8, 9]
print ("This is Tic Tac Toe / Noaughts and Crosses")
print ('(x)Human against (o) "machine"')
print (boardt)
print (boardm)
print (boardd)
hpos = int(input("Pick a position "))
if hpos == 1:
boardt.remove(1)
boardt.insert(0,"X")
mpos = (int(random.randint(1,8)))
if mpos == 1 or 2:
boardt.remove(mpos)
boardt.insert(mpos,"O")
elif mpos == 3 or 4 or 5:
boardm.remove(mpos)
boardm.insert(mpos,"O")
elif mpos == 6 or 7 or 8:
boardd.remove(mpos)
boardd.insert(mpos,"O")
错误:
Traceback (most recent call last):
File "main.py", line 16, in <module>
boardt.remove(mpos)
ValueError: list.remove(x): x not in list
解决方案
主要问题是 egif mpos == 1 or 2
不测试值是 1 还是 2。
测试应该是if mpos == 1 or mpos == 2:
,或者更好:if mpos in (1, 2):
推荐阅读
- xml - XQuery 的这个输出是否正确?
- javascript - 如何将非unicode转换为unicode?
- php - 在 wordpress 的 php 代码中显示 gif
- excel - 使用 VB.Net 将文本文件导入到 Excel 工作簿
- mysql - MySQL Workbench 从 CSV 导入 NULL
- meteor - 使用流星和简单模式获取无法读取未定义的属性“电子邮件”
- swift - 从 Firebase 存储获取 pdf
- omnet++ - Omnet++,即将抛出一个cRuntimeError异常
- git - 为什么接收后挂钩不起作用?
- php - SQL,把最常见的国家放在最前面,然后放在下面