如果类型错误,返回Fals

2024-05-15 23:24:52 发布

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

我创建了一个python函数:

def is_cayley_table(table):
    try:
        if type(table) is not list:
            return False
        else:
            n = len(table)
            poss_values = range(0,n)
            for i in range(0,n):
                if len(table[i]) != n:
                    return False
            for j in range(0,n):
                if type(table[i][j]) is int and table[i][j] in poss_values:
                    return True
                else:
                    return False
    except TypeError:
        return False

然后用无效参数调用函数:

is_cayley_table([1, 1, 0], [0, 1, 2], [1, 2, 2])

我希望函数返回“False”,但现在我得到了:

 File "C:/Users/Jack/OneDrive/Documents/comp_project.py", line 27, in <module>
    is_cayley_table([1, 1, 0], [0, 1, 2], [1, 2, 2])

TypeError: is_cayley_table() takes 1 positional argument but 3 were given

如果有人能帮忙,我将非常感激。你知道吗

杰克


Tags: 函数infalseforlenreturnifis
2条回答

首先,您不能为函数提供比它声明的参数更多的参数。这是这里最大的问题。你知道吗

如果你给函数提供一个参数

is_cayley_table(([1, 1, 0], [0, 1, 2], [1, 2, 2]))

它将按预期工作

您正在捕获函数中的类型错误,但问题出在调用函数中;这不能在函数本身中捕获。你知道吗

我不知道为什么您需要能够使用无效参数调用函数,但支持这一点的一种方法是接受具有*args语法的任何参数,然后检查您拥有的:

def is_cayley_table(*args):
    if len(args) != 1:
        return False
    table = args[0]
    ...

相关问题 更多 >