[Tutor] Is there a library which has this object?

Alan Gauld alan.gauld at yahoo.co.uk
Sat Apr 30 20:53:51 EDT 2016


On 30/04/16 08:48, Yeh wrote:

> start = input("please input the value of start: ")
> end = input("please input the value of end: ")
> dur = input("please input the value of dur: ")
> array = np.linspace(float(start),float(end),1000)
> dur = float(dur)/len(array)
> for i in array:
> print(float(i))
> time.sleep(dur)

Since you say it works I assume you are still not posting
in plain text since it would need indentation after
the for loop.

> and it worked, then, I was trying to make it as a function:
> 
> def myFunction(start,end,dur):
> ...........

I don;t know what the dots are. They should give you an error!

> for i in array:
> return i
> time.sleep(dur)
> 
> there is no errors. because it just post the first number in the array, 

Your problem is that return always returns the value and
exits the function. Next time you call the function it
starts again from the beginning.

I think you are looking to create a generator which is
a function that returns a value but next time you call
the function it carries on where it left off.
The good news is that this is easy, just substitute
yield for return. The next problem is to make the function
increment the value each time and for that you need a loop.

def make_numbers(start, end):
    while start <= end:
       yield start

Notice I've removed the duration parameter because that's
better done outside the function (a function should do
only one thing, in this case generate numbers).

We can access the numbers and introduce a delay with:

for n in make_numbers(float(start),float(end))
    print (n)
    time.sleep(float(dur))

But of course that's pretty much what the built in
range() function does for you anyway.

for n in range(float(start), float(end)):
    print(n)
    time.sleep(float(dur))

> I have checked the cycle(), and yes, that is what I'm searching! 

> how to stop cycle() by manual?
> such as press "q", then break the cycle(). 

You will need to include a command to read the
keyboard during your loop. How you do that depends
on your needs and maybe your OS. You can use input()
but the user then needs to hit a key every loop iteration.
Or you can use getch() from curses on Linux or from
msvcrt on Windows if you don't want the user to  have
to hit enter each time.

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