int 不可作为if语句的可迭代对象

2024-10-16 20:47:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个井字游戏,我正在为网格上的位置创建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'


Tags: 代码网格游戏returnifdef错误语句
3条回答

怎么办

def get_move():
    while True:
        xy = input("Enter your move (ie b2): ").strip().lower()
        if len(xy) == 2:
            x, y = xy
            if x in "abc" and y in "123":
                return (ord(x) - ord("a"), ord(y) - ord("1"))

它跑起来像

^{pr2}$

我认为您实际上是在更早地遇到错误(如果您在问题中包含错误堆栈,这将有助于我们):

for i in y:
     acc.append(i)

如果希望用户以[letter, number]格式以字符串形式输入列表,则需要使用astmodules^{}方法

像这样:

^{pr2}$

因此,当用户在提示下输入:

Enter your move [letter, number]: ['a', 3]

ast.literal_eval(y)将把输入转换成python列表['a', 3]。在

以下代码正确打印x和y的值:

^{4}$

演示:

$ python3 so.py
Enter your move [letter, number]: ['a', 1]
a 1

但是,如果希望用户以letter number格式输入一个不带方括号的字符串,那么您的代码仍然无法实现预期的效果。因为y将有字符串a 3(如果输入是'a3')。做一个

for i in y:
     acc.append(i)

将使acc成为三个元素的列表['a', ' ', '3']y[1]现在是一个空格字符。所以代码y=int(acc[1])中的这一行将失败。在

请试试这个:

def getXandY():
    y=raw_input("Enter your move [letter, number]: ")
    input_list = y.split(',')
    acc=[]
    for i in input_list:
        acc.append(i)

我假设输入如下:a,1
您只需修改我上面提到的部分,它将接收到您输入的字母和数字,并用逗号分隔。
它在我的电脑里工作得很好。希望有帮助。。在

相关问题 更多 >