我正在制作一个井字游戏,我正在为网格上的位置创建if语句(即(a,1)(b,2)(c,3)等。)
一旦代码到达我的第一个if语句,我就一直得到“'int'object is not iterable”。在
当前代码:
def getXandY():
y=input("Enter your move [letter, number]: ")
acc=[]
for i in y:
acc.append(i)
y=int(acc[1])
x=acc[0]
print(x,y)
if y == 1:
return 0
print(x,y)
if y == 2:
return 1
print(x,y)
if y == 3:
return 2
else:
return -1
x=x.lower()
num=convrtLet2Num(x)
return num,y
def convrtLet2Num(x):
if x == 'a':
return 0
if x== 'b':
return 1
if x== 'c':
return 2
else:
return -1
我到达了第一个“print(x,y)”的位置,然后错误发生在if语句中。你知道是什么导致了这个错误吗?在
在我测试y=1和x='a'
怎么办
它跑起来像
^{pr2}$我认为您实际上是在更早地遇到错误(如果您在问题中包含错误堆栈,这将有助于我们):
如果希望用户以} 方法
[letter, number]
格式以字符串形式输入列表,则需要使用ast
modules^{像这样:
^{pr2}$因此,当用户在提示下输入:
ast.literal_eval(y)
将把输入转换成python列表['a', 3]
。在以下代码正确打印x和y的值:
^{4}$演示:
但是,如果希望用户以
letter number
格式输入一个不带方括号的字符串,那么您的代码仍然无法实现预期的效果。因为y
将有字符串a 3
(如果输入是'a3')。做一个将使
acc
成为三个元素的列表['a', ' ', '3']
。y[1]
现在是一个空格字符。所以代码y=int(acc[1])
中的这一行将失败。在请试试这个:
我假设输入如下:
a,1
您只需修改我上面提到的部分,它将接收到您输入的字母和数字,并用逗号分隔。
它在我的电脑里工作得很好。希望有帮助。。在
相关问题 更多 >
编程相关推荐