Welcome to Python!

Python is an open-source programming language which favors simplicity and readability. It is available for Windows and already installed on most linux systems. Due to its power and ease of use, it has gained wide acceptance in scientific communities.

Look at the following example code:

What do you think it will do? “from LEDs import *” opens a file called LEDs.py which does some work behind the scenes and give you access to a function called LED(). Hit F5 or [Run] -> [Run Module] to start the program. Hit “ctrl-C” to stop.

Why does the light continue to blink? Does the indentation matter or is it just for looks?

Python has an interactive window which is very helpful. After running the program once, type help(LED) to see it’s description:
What if you just wanted it to blink five times? Try the following code in the interactive window to see what it does:
>>>for x in range(5):
  print “x =” , x

Adapt this code to make the LED blink a limited number of times.

If you are curious, open LEDs.py (see below) to see what is hidden in the module!

Learn more and download at: http://www.python.org


Search Maker's Box for Python

# LEDs.py

#import RPi.GPIO as GPIO
import time
import sys


for pin in [11, 12, 13]:
   #GPIO.setup(pin, GPIO.OUT)

def LED(pin, state):
   '''Turns LED on (True) or off (False).'''
   if state not in [True, False]:
       print "Only correct state for LED is:\n"
       print "   True or False\n"
   if state:
       #GPIO.output(pin, GPIO.HIGH)
       print pin, " HIGH"
       print pin, " LOW"
       #GPIO.output(pin, GPIO.LOW)

if __name__ == "__main__":
   for i in range(5):
       for pin in [11, 12, 13]:
           LED(pin, True)
           LED(pin, False)


# stoplight.py

from time import sleep
from LEDs import *

green = 11
yellow = 12
red = 13
ON = True
OFF = False

while True:
   LED(green, ON)
   LED(green, OFF)

No comments:

Post a Comment