为什么这个代码在运行时没有返回一个值?

2024-09-27 17:41:08 发布

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

代码如下:

def row_check(table):
    for ealst in table:
            first = [ealst[0]]
            for each in ealst[1:]:
                    if each not in first:
                            first.append(each)
                    else:
                            return False
    return True

def col_check(table):
    col = []
    totalcol = []
    count = 0
    for rows in table:
            for columns in range(len(table)):
                    col.append(table[int(columns)][count])
            count += 1
            totalcol.append(col)
            col = []
    return totalcol

def check_sudoku(table):
    if row_check(table) and row_check(col_check(table)):
            return True
    return False

if __name__ == '__main__':
    table = [[1, 2, 3],
             [4, 5, 6],
             [7, 8, 9]]
    check_sudoku(table)

这不是返回值True。现在,当我在代码运行后手动调用函数时,它将返回预期值:

>>> table
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> check_sudoku(table)
True

下面是一个展示相同行为的最小示例:

def check_sudoku(table):
    return True

if __name__ == '__main__':
    table = [[1, 2, 3],
             [4, 5, 6],
             [7, 8, 9]]
    check_sudoku(table)

为什么会发生这种情况,我如何防止这种情况,即调用时返回True?你知道吗


Tags: intrueforreturnifdefchecktable
1条回答
网友
1楼 · 发布于 2024-09-27 17:41:08
if __name__ == '__main__':
    table = [[1, 2, 3],
             [4, 5, 6],
             [7, 8, 9]]
    print check_sudoku(table) #you need to actually print stuff when running in a script 

当您在shell中时,它只打印返回值。当你运行一个脚本时,你必须打印任何你想打印的东西。。。你知道吗

相关问题 更多 >

    热门问题