TypeError:if语句中的“str”和“int”的操作数类型不受支持

2024-10-16 20:40:00 发布

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

我想做一个井字游戏。这段代码适用于Python2,但不适用于Python3

代码如下:

gameList = []
for i in range(9):
    gameList.append(' ')

while True:
    while True:
        x = input('Which square? ')
        if(gameList[x-1] == ' '):
            gameList[x-1] = 'X'
            printgame()
            break

        else:
            print('Choose an unchosen square.')
            continue

    while True:
        y = random.randint(0,8)
        if(gameList[y] == ' '):
             gameList[y] = 'O'
             printgame()
             break
        else:
             print('Choose an unchosen square.')
             continue

Tags: 代码antrueifelseprintsquarebreak
2条回答

在Python3中,输入函数以字符串形式返回变量,即使它是输入的整数。将变量x转换为整数,这样就可以了

        x = int(input('Which square? '))

这里的问题是:x-1(str-int:在python中是不允许的),x是一个str(输入法返回的值),您应该首先将x强制转换为int

      x = int(input('Which square? '))

相关问题 更多 >