【问题标题】:RuntimeError: generator raised StopIterationRuntimeError:生成器引发 StopIteration
【发布时间】:2020-07-29 14:20:53
【问题描述】:

我正在上课并试图找出我的问题。我不明白为什么如果我输入的不是 9 位数字,if 应该提高StopIteration,然后我希望它转到except 并打印出来。有什么问题?

def check_id_valid(id_number):
    if len(str(id_number)) != 9: raise StopIteration
    else:
        lst_id = list(map(int,str(id_number)))
        lst_id[1::2] = map(lambda x: x * 2, lst_id[1::2])
        lst_id = map(lambda x: (x % 10 + x // 10), lst_id)
        num1 = sum(lst_id)
        if num1 % 10 == 0:
            return True
        else:
            return False

def id_gen(id2):
    index = 0
    while index < 10:
        id2 += 1
        if check_id_valid(id2):
            index += 1
            yield id2

def main():
    try:
        gen_idnum = id_gen(int(input("Enter id number : ")))
        for n in gen_idnum:
            print(n)

    except StopIteration as e:
        print(e)
    except ValueError as e:
        print(e)

if __name__ == '__main__':
    main()

【问题讨论】:

  • 你为什么要提高 StopIteration 而不是像 ValueError 这样的理智的东西? StopIteration 服务于a very specific purpose(允许__next__ 方法指示迭代已完成),如您所见,将其重用于其他目的会导致问题。此处转换为RuntimeError 可以节省您的时间;如果 Python 没有这样做,生成器将默默地停止迭代(StopIteration 被默默吞下,导致迭代结束而不传播异常;无论如何你永远都不会捕获它)。

标签: python python-3.x


【解决方案1】:

将评论转换为答案,因为它显然回答了 OP 的问题:

不要提StopIteration,提一些像ValueError这样理智的东西。

StopIteration 服务于a very specific purpose(允许__next__ 方法指示迭代已完成),并且将其重用于其他目的会导致问题,正如您所见。此处转换为RuntimeError 可以节省您的时间;如果 Python 没有这样做,生成器将默默地停止迭代(StopIteration 被默默吞下,导致迭代结束而不传播异常;无论如何你永远都不会捕获它)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2019-01-13
    • 2021-07-30
    • 2020-01-20
    • 1970-01-01
    • 2021-11-01
    • 2018-03-26
    相关资源
    最近更新 更多