【发布时间】: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