Learning Python 3 with the Linkbot/Using Modules
Here's this chapter's typing exercise (name it cal.py (
import actually looks for a file named calendar.py and reads it in. If the file is named calendar.py and it sees a "import calendar" it tries to read in itself which works poorly at best.)):
import calendar year = int(input("Type in the year number: ")) calendar.prcal(year)
And here is part of the output I got:
Type in the year number: 2001 2001 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 1 2 3 4 1 2 3 4 8 9 10 11 12 13 14 5 6 7 8 9 10 11 5 6 7 8 9 10 11 15 16 17 18 19 20 21 12 13 14 15 16 17 18 12 13 14 15 16 17 18 22 23 24 25 26 27 28 19 20 21 22 23 24 25 19 20 21 22 23 24 25 29 30 31 26 27 28 26 27 28 29 30 31
(I skipped some of the output, but I think you get the idea.) So what does the program do? The first line
import calendar uses a new command
import. The command
import loads a module (in this case the
calendar module). To see the commands available in the standard modules either look in the library reference for python (if you downloaded it) or go to http://docs.python.org/library/. If you look at the documentation for the calendar module, it lists a function called
prcal that prints a calendar for a year. The line
calendar.prcal(year) uses this function. In summary to use a module
import it and then use
module_name.function<code> for functions in the module. Another way to write the program is:
from calendar import prcal year = int(input("Type in the year number: ")) prcal(year)
This version imports a specific function from a module. Here is another program that uses the Python Library (name it something like clock.py) (press Ctrl and the 'c' key at the same time to terminate the program):
from time import time, ctime prev_time = "" while True: the_time = ctime(time()) if prev_time != the_time: print("The time is:", ctime(time())) prev_time = the_time
With some output being:
The time is: Sun Aug 20 13:40:04 2000 The time is: Sun Aug 20 13:40:05 2000 The time is: Sun Aug 20 13:40:06 2000 The time is: Sun Aug 20 13:40:07 2000 Traceback (innermost last): File "clock.py", line 5, in ? the_time = ctime(time()) KeyboardInterrupt
The output is infinite of course so I canceled it (or the output at least continues until Ctrl+C is pressed). The program just does a infinite loop (<code>True is always true, so
while True: goes forever) and each time checks to see if the time has changed and prints it if it has. Notice how multiple names after the import statement are used in the line
from time import time, ctime.
The Python Library contains many useful functions. These functions give your programs more abilities and many of them can simplify programming in Python.
Linkbot Buttons and the
The following program uses the
random module to generate random numbers. Basic usage is like this:
import random # Imports the module x = random.randint(0, 100)
The previous little code snipped produces a random number between 0 and 100 and puts it in the variable
x. The arguments to
randint() control the range of the random number generated. For instance, if you instead wanted a random number between -100 and +100, you could do
x = random.randint(-100, 100)
The following Linkbot program uses the
random module to change the LED color to some random colors.
# File: 01_rand_color_button.py # This program changes the Robots LED color every time you press the "B" button # on the robot. import linkbot #imports the module with the Linkbot commands import random #imports a random integer generator robotID = input('Enter robot ID: ') #prompts user to enter Linkbot ID robot = linkbot.CLinkbot(robotID) def myCallback(buttons, event, timestamp): global robot if buttons & 0x02: robot.setLedColor( #calls setLEDColor from 'barobo' module random.randint(0, 255), #uses the 'random' integer generator from random.randint(0, 255), #the random module to set colors random.randint(0, 255) ) robot.enableButtonEvents(myCallback) input('Press "Enter" to quit.')
Notice in the Linkbot program that we define a new function called "myCallback". However, you will notice in our code that we never actually call our function. The only other place it appears is inside a function called
robot.enableButtonEvents(). The function
myCallback is what is known as a "callback function". A callback function is a function that is written by a programmer, but the programmer doesn't actually call the function anywhere in their code. Instead, the programmer tells the computer program to call that function any time a certain event happens. In our case, by putting the function into the
enableButtonEvents function, we are telling the program to call our callback function,
myCallback, every time a button is pressed or released on the Linkbot.
Inside of the function
myCallback, you will notice a line that reads
global robot. The
global keyword tells Python not to create a new variable, but instead use a variable in a higher scope that has already been declared. In this case, it tells Python to look for an existing variable called "robot" and use that.
You can only use the
global keyword to find variables that are in an outer scope than where the
global keyword is used. For instance, the following code is fine:
x = 5 def myFunc(): global x print(x) # Prints the current value of x, which is 5 myFunc() # Call our function "myFunc"; should print "5"
However, This code will not work:
def myFunc(): x = 5 def myOtherFunc(): global x # This will not work! print(x) myOtherFunc()
The previous code snippet will not work because the variable "x" is trapped inside the function
myFunc(). Variables referred to with
global need to be in the parent scope of where the
global keyword is used.
Check out the range of colors and intensity the Linkbot is capable of generating with its built in RGB LED.
high_low.py program from section Decisions to use an random integer between 0 and 99 instead of the hard-coded 78. Use the Python documentation to find an appropriate module and function to do this.
the high_low.py program from section Decisions to use an random integer between 0 and 99 instead of the hard-coded 78. Use the Python documentation to find an appropriate module and function to do this.
from random import randint number = randint(0, 99) guess = -1 while guess != number: guess = int(input ("Guess a number: ")) if guess > number: print("Too high") elif guess < number: print("Too low") print("Just right")