根据我是使用函数还是n获取TypeError

2024-06-11 08:45:54 发布

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

在我的tic-tac-toe游戏中,我经常遇到这个错误:TypeError: unsupported operand type(s)对于%
list''int'

我有一个“turns”变量来计算已通过的圈数,并有一个充当板的字符串列表

给定此代码:

def x_or_o(t):
    """Check the number of turns for an even number and return a string."""
    if t % 2 == 0:
        return 'O'
    else:
        return 'X'

def place_char(i, t, brd):
    """Change the value of an item in the board list from an 'e' to an 'X' or
    'O'."""
    brd[int(i) - 1] = '{}'.format(x_or_o(t))

def turn(t, brd):
    """Read player input and print symbol onto the board."""
    print("Player {}'s turn.".format(x_or_o(t)))
    p_input = input('1-9: ')
    check_quit(p_input)
    if brd_empty(p_input, brd):
        place_char(p_input, brd, x_or_o(t))
        # brd[int(p_input) - 1] = '{}'.format(x_or_o(t))
    ...

当我在turn()if语句中使用place_char()时,我得到一个TypeError。但是,当我将行从place_char()直接复制并粘贴到turn()时,我的代码运行良好

为什么我在使用函数时出错,而不是在使用函数中的代码时出错


Tags: ortheanformatinputreturnifdef
1条回答
网友
1楼 · 发布于 2024-06-11 08:45:54
def place_char(i, brd, xo):
    """Change the value of an item in the board list from an 'e' to an 'X' or
    'O'."""
    brd[int(i) - 1] = '{}'.format(xo)

你能试着用这个方法替换你的place_char方法吗

方法中的错误:

  • 在方法签名place_char(i, t, brd)中,顺序不同
  • 您再次调用x_or_o,其中tplace_char内,但您已经将x_or_o(t)的输出传递给了place_char方法

相关问题 更多 >