[Tutor] taking support of strings in solving numerical problems

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


On 26/10/2020 02:15, Manprit Singh wrote:

> def ser_gen(no, order):
>     f_no = no
>     for i in range(order):
>         yield f_no
>         f_no = f_no*10 + no
> 
> all(ser_gen(9, -3))     Returns True that says, there is an empty iterable
> inside all( )
OK, I confess that surprised me as I expected the "faulty" ser_gen to
return none since it falls off the bottom of the function.
But it seems a generator raises StopIteration when that happens:

>>> list(ser_gen(9,3))
[9, 99, 999]
>>> list(ser_gen(9,-3))
[]
>>> next(ser_gen(9,-3))
Traceback (most recent call last):
  File "<pyshell#93>", line 1, in <module>
    next(ser_gen(9,-3))
StopIteration

And that in turn results in all() and list() seeing an empty sequence.

This should be in the language reference document under generator
functions but I haven't gone looking for it... An exercise for the reader?

However, the real takeaway from this is that you should check
for invalid input at the start of your functions. And ensure that there
are no default exists in a function that should return something.
If you defined the function as:

def ser_gen(no, order):
    no,order = int(no),int(order)
    if order <= 0: raise ValueError("order must be > 0")
    f_no = no
    for i in range(order):
        yield f_no
        f_no = f_no*10 + no
    else: raise StopIteration   # make explicit

There would be no surprises and there would be useful errors.

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