如何仅在 Python 中到达循环结束后才打印失败语句?

How to print a fail statement only after reaching end of loop in Python?

我有一小段代码,需要帮助来实现失败语句 (No match)。这是片段:

for row in reader:
    # converts each string num --> int num
    i = 1
    while i < len(row):
        row[i] = int(row[i])
        i += 1

    if STR_count_large(sequence) == row[1:]:
        print(row[0])

    if STR_count_small(sequence) == row[1:]:
        print(row[0])

我遍历名为 readercsv 文件中的每个 row,并将该行中的每个元素从字符串转换为 int。之后,我将该特定行的列表内容(从第一个元素到末尾)与每个包含一个列表的两个函数进行比较。如果两个列表匹配,我打印 row[0],它只包含匹配列表所属的人的姓名。但是,如果这两个 if 语句在通过 for row in reader: 循环后都失败了,我将如何只打印一次像 No match 这样的语句?因为如果我把它写在循环中,这个语句会被打印 row 次而不是一次。

编辑: 这是我使用 bschlueter 的想法的(不成功的)实现。任何帮助将不胜感激:

exceptions = list()
            for row in reader:
                # converts each string num --> int num
                i = 1
                while i < len(row):
                    row[i] = int(row[i])
                    i += 1
                try:
                    if STR_count_large(sequence) == row[1:]:
                        print(row[0])
                    if STR_count_small(sequence) == row[1:]:
                        print(row[0])
                except (STR_count_large(sequence) != row[1:] and STR_count_small(sequence) != row[1:]) as exception:
                    exceptions.append(exception)
            if exceptions:
                print("No match")

你可以累积错误,然后在循环完成后检查累积:

exceptions = list()
for row in reader:
    try:
        do_a_thing(row)
    except MyException as exception:
        exceptions.append(exception)
# Do something if any exceptions were added to the list
if exceptions:
    handle_exceptions(exceptions)

只需再添加一个带有 and 的 if 语句即可捕获并打印不匹配项。 在第二个 IF 语句的末尾添加这个

if row == reader[len(reader)]:#Check for last iteration
    if STR_count_large(sequence) != row[1:]: and STR_count_small(sequence) != row[1:]:
        print("No Match")