Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

python - RuntimeError: generator raised StopIteration

I am in a course and try to find my problem. I can't understand why if I enter something other than 9 digits, the if should raise the StopIteration and then I want it to go to except and print it out. What is the problem?

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Converting comment to answer since it apparently answered the OP's question:

Don't raise StopIteration, raise something sane like ValueError.

StopIteration serves a very specific purpose (to allow a __next__ method to indicate iteration is complete), and reusing it for other purposes will cause problems, as you've seen. The conversion to RuntimeError here is saving you; if Python hadn't done that, the generator would have silently stopped iterating (StopIteration is swallowed silently, causing iteration to end without propagating the exception; you'd never catch it anyway).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...