[英]Getting StopIteration error in generator function
I'm using a generator function to returns 10 ' valid ' numbers one after the other.我正在使用生成器函数一个接一个地返回 10 个“有效”数字。
The check_id_valid()
function returns True
or False
depending on whether the number is valid or not. check_id_valid()
函数根据数字是否有效返回True
或False
。 The problem is that I'm getting a StopIteration
error after producing only one valid number.问题是我在仅生成一个有效数字后收到
StopIteration
错误。
The check_id_valid()
function is working well, I checked it by sending it parameters directly: print(check_id_valid(123456780))
. check_id_valid()
函数运行良好,我通过直接发送参数来检查它: print(check_id_valid(123456780))
。
The generator function:生成器功能:
def id_generator(Id_number):
Id_number +=1
valid_id = (check_id_valid(Id_number))
while not valid_id:
Id_number += 1
valid_id = check_id_valid(Id_number)
yield Id_number
def main():
id_gen = id_generator(123456780)
try:
for item in range(10):
print(next(id_gen))
except (illigalDigits, illigalException) as e:
print(e)
if __name__ == "__main__":
main()
The error:错误:
print(next(id_gen))
StopIteration
>>>
Your generator function only yield
s once, so needs to be changed to do so more than that.您的生成器函数只
yield
一次,因此需要进行更多更改以做到更多。 Here's a runnable example and the output it produces:这是一个可运行的示例及其产生的输出:
# A little scaffolding to make code runnable.
class illigalDigits(Exception): pass
class illigalException(Exception): pass
def check_id_valid(id):
return id # Consider anything valid.
########
def id_generator(Id_number):
while True:
Id_number += 1
valid_id = check_id_valid(Id_number)
if valid_id:
yield Id_number
def main():
id_gen = id_generator(123456780)
try:
for _ in range(10):
print(next(id_gen))
except (illigalDigits, illigalException) as e:
print(e)
if __name__ == "__main__":
main()
Output:输出:
123456781
123456782
123456783
123456784
123456785
123456786
123456787
123456788
123456789
123456790
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.