RuntimeError: generator raised StopIteration

2024/9/22 8:29:05

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 StopIterationelse: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 Trueelse:return Falsedef id_gen(id2):index = 0while index < 10:id2 += 1if check_id_valid(id2):index += 1yield id2def 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()
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).

https://en.xdnf.cn/q/119155.html

Related Q&A

split list elements into sub-elements in pandas dataframe

I have a dataframe as:-Filtered_data[defence possessed russia china,factors driving china modernise] [force bolster pentagon,strike capabilities pentagon congress detailing china] [missiles warheads, d…

Image does not display on Pyqt [duplicate]

This question already has an answer here:Why Icon and images are not shown when I execute Python QT5 code?(1 answer)Closed 2 years ago.I am using Pyqt5, python3.9, and windows 11. I am trying to add a…

Expand the following dictionary into following list

how to generate the following list from the following dictionary d = {2: 4, 3: 1, 5: 3}f = [2**1,2**2, 2**3, 2**4, 3**1, 5**1, 5**2, 5**3, 2**1 * 3, 2**2 * 3, 2**3 * 3, 2**4 * 3, 5**1 * 3, 5**2 * 3, 5*…

how can I improve the accuracy rate of the below trained model using CNN

I have trained a model using python detect the colors of the gemstone and have built a CNN.Herewith Iam attaching the code of mine.(Referred https://www.kaggle.com) import os import matplotlib.pyplot a…

Classes and methods, with lists in Python

I have two classes, called "Pussa" and "Cat". The Pussa has an int atribute idPussa, and the Cat class has two atributes, a list of "Pussa" and an int catNum. Every class …

polars dataframe TypeError: must be real number, not str

so bascially i changed panda.frame to polars.frame for better speed in yolov5 but when i run the code, it works fine till some point (i dont exactly know when error occurs) and it gives me TypeError: m…

Get a string in Shell/Python using sys.argv

Im beginning with bash and Im executing a script :$ ./readtext.sh ./InputFiles/applications.txt Here is my readtext.sh code :#!/bin/bash filename="$1" counter=1 while IFS=: true; doline=read …

Need to combine two functions into one (Python)

Here is my code-def Max(lst):if len(lst) == 1:return lst[0]else:m = Max(lst[1:])if m > lst[0]: return melse:return lst[0] def Min(lst):if len(lst) == 1:return lst[0]else:m = Min(lst[1:])if m < ls…

Error: descriptor blit requires a pygame.Surface object but received a NoneType [duplicate]

This question already has answers here:How can I draw images and sprites in Pygame?(4 answers)Closed 2 years ago.I am creating a game. I wrote this code to create a sprite and its hitbox:hg = pygame.i…

How can I deal with overlapping rectangles? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 5 years ago.Improve…