首页 > 解决方案 > 如何在没有 try / except 的情况下终止生成器并引发 StopIteration?

问题描述

我正在尝试终止我创建的生成器函数的迭代,而不会在StopIteration遇到程序时立即终止。我知道我可以使用try/except语句来捕获抛出的异常,但是有没有办法在不抛出异常的情况下终止生成器函数?

我的代码:

def isPalindrome(num):
    if num == int(str(num)[::-1]):
        return True
    return False

def palindrome_special():
    num = 0
    while True:
        if isPalindrome(num):
            yield num
            if len(str(num)) == 10:
                raise StopIteration
            num = 10 ** len(str(num)) #If palindrome is encountered, a reassignment takes place to calculate the next palindrome containing 1 more digit
        num = num + 1

for i in palindrome_special():
    print(i)

标签: pythonpython-3.xexceptioniteratorgenerator

解决方案


不需要终止生成器。当我们让它停止产生值时,它只会停止产生值。使用 if 语句重写代码并在生成器函数中使用 break 即可。

    def isPalindrome(num):
        if num == int(str(num)[::-1]):
            return True
        return False
    
    def palindrome_special():
        num = 0
        while True:
            if isPalindrome(num):
                if len(str(num)) <= 10: #If statement
                    yield num
                else: #condition that terminates the generation of values
                    break
                num = 10 ** len(str(num))
            num = num + 1
    
    for i in palindrome_special():
        print(i)

推荐阅读