如何在没有 try / except 和 raise StopIteration 的情况下终止生成器?

How to terminate a generator without try / except and raise 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)

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

    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)