[Tutor] Random time code

Alan Gauld alan.gauld at yahoo.co.uk
Fri Aug 19 13:28:18 EDT 2016


On 18/08/16 12:41, Simon Le-Talbot wrote:
> Hi , I have recently purchased a Raspberry pi3 and 
> I am wanting to turn a light on and then have it 
> turn off at a random time between 3 and 8 seconds. 

The time module will give you the current time
in seconds. It also provides the sleep() function
which lets your program pause(sleep) for a
number of seconds.

sleep(...)
    sleep(seconds)

    Delay execution for a given number of seconds.  The argument may be
    a floating point number for subsecond precision.
(END)

For randomness look at the random module which
includes several different random number generation
functions. One of them, randrange() probably suits
your needs best.

randrange(start, stop=None, step=1, _int=<class 'int'>) method of
random.Random instance
    Choose a random item from range(start, stop[, step]).

    This fixes the problem with randint() which includes the
    endpoint; in Python this is usually not what you want.
(END)

If you need more help in assembling the parts let us know.
But I didn't want to spoil your fun in figuring it out. :-)


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