[Tutor] taking support of strings in solving numerical problems

Alan Gauld alan.gauld at yahoo.co.uk
Mon Oct 26 07:04:21 EDT 2020


On 26/10/2020 09:23, Manprit Singh wrote:

>>>> next(ser_gen(9, "A"))                      # execution of generator
> TypeError: 'str' object cannot be interpreted as an integer
>>>> next(ser_gen(9, -3))                       # execution of generator
> StopIteration
>>>>
> 
> 1) In the first  execution of the function call, since "A" is string , and
> range cannot accept a string, hence Type error is generated .
> 2) In the second  execution of the function call, since -3 is negative
> integer, the for loop never got executed, The function has  returned an
> empty iterator, this is proved with the fact that next( ) has caused
> StopIteration .

Yes, that is correct.

> And finally a mechanism is needed in the program to deal with these
> unexpected behaviours - like exception handling .

Yes, the user of the function should handle the exceptions if possible.
But the writer of the function - you - should test for and raise any
errors that may cause unexpected problems.

That's why, in my version, I added the int() conversions(which will
raise Value or type errors for invalid input).  And raised a ValueError
for zero/negative second values.

You could of course catch those internally and return an empty
list which would mean the function always returned an iterator
of some sort, or you could raise StopIteration for all errors which
would have a similar impact. But then the user would be blissfully
unaware of their invalid data issues and that could cause worse
problems later. It's better to raise accurate and descriptive
errors as early as possible.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list