[Tutor] Help needed
Alan Gauld
alan.gauld at btinternet.com
Thu Feb 4 19:38:24 EST 2016
On 04/02/16 23:26, Tom Brodle wrote:
> While true:
> Turn LED on
> sleep 5 seconds
> Turn LED off
> sleep .5 seconds
> # Coming from the world of Basic I did/do not understand what made the program loop
> # back to while True: line of code.
Its the indentation
In BASIC you would write
WHILE TRUE
TURN LED ON
SLEEP 5s
TURN LED OFF
Sleep 0.5s
WEND
In Python the Wend is implicit in the indentation.
> # I wanted the LED to turn on and then off and stay off,
In that case you didn't want a while loop, you just
wanted a sequence:
Turn LED on
sleep 5 seconds
Turn LED off
> # page I became aware of quit(code=None) and inserted it
That quits the entire program.
That's OK if that's what you want but if yyou need to do
something else after wards its not too helpful.
If you really want to break out of a 'while True' loop you
need to use the 'break' statement, usually inside some
kind of if statement
while True
if some condition:
break # exit the loop
do whatever the loop does
> GPIO.cleanup()
> # I was told to put this line in but I do not know where it goes
Probably after the loop - that is without any indentation.
You are best to put it in a 'finally' clause like this
try:
while True:
loop code here
finally: # always executed
GPIO.cleanup()
Then even if you hit an error condition that forces an exit
from the loop the finally is guaranteed to be executed.
> #The code did turn the LED on once and then it did stay off,
> but it gave me a message that the program is still running.
> I did not think that programs actually did stop until the
> power was removed.
Probably not because the while never exits.
BTW the LED is not really staying on from the look of things.
Its turning on for 5 seconds then off for 0.5s. Its just that
the off is too short to notice.
For more about Python loops you can check out my tutorial below.
(While loops are coverd about half way down the loops topic)
If you know BASIC the examples are nearly all repeated in
VBScript (a form of BASIC) so you should recognise the patterns.
--
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