[Tutor] taking support of strings in solving numerical problems
Alan Gauld
alan.gauld at yahoo.co.uk
Sun Oct 25 08:26:08 EDT 2020
On 25/10/2020 08:38, Manprit Singh wrote:
>>>> genfx_ser(9, "a")
> <generator object genfx_ser at 0x7f38bf690190>
>
> In the second function call , see the second argument is "a", which is
> being passed to formal parameter lim in function definition, must create
> an error , since range cannot accept a non integer value, but still
> function call is returning a generator object.
This is one of the differences between a generator and a function.
You can assign the generator to a variable then iterate over it.
Its only when you start the iteration that the code actually gets
executed and the error raised.
So for example:
>>> def f(x,n):
nums = x
for i in range(n):
yield nums
nums = nums*10 + x
>>> f(9,3)
<generator object f at 0x7fd53c0a39e0>
>>> list(f(9,3))
[9, 99, 999]
>>> f(9,'a')
<generator object f at 0x7fd53c0a39e0>
>>> list(f(9,'a'))
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
list(f(9,'a'))
File "<pyshell#54>", line 3, in f
for i in range(n):
TypeError: 'str' object cannot be interpreted as an integer
>>>
You could have multiple sequences stored in variables
and then call whichever sequence is required depending
on user input. But they are all based on the same
generator function.
> Is it a bug ?
No, its a feature! :-)
--
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