Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...