You can close your Python script file; let’s work directly in the Python Shell. First, I want to discuss three Python programming features in a bit more detail:
variables type casting concatenation
I’m calling out these three programming tools because they are so fundamental not only to Python, but to any programming language. For instance, most computer programs take data and perform some sort of processing and evaluation on it. How and where do you store that data? What if you need to convert data from one form to another—how is that done in Python? Finally, how do you combine multiple pieces of dynamic data?
Read on, friend...read on.
Variables
As previously discussed, a variable is a named placeholder for data. Variable naming in Python 3 is flexible, but there are a few rules that you need to keep in mind:
Python key words cannot be used as a variable name (naming a variable print is not allowed, for instance).
Variable names cannot contain spaces (underscores are okay, though).
Uppercase and lowercase characters are distinct (Var1 and var1 are considered two separate variables).
The first character of a variable name must be a letter a through z, A through Z, or an
underscore character (no numbers to start variable names because this confuses the Python interpreter).
After the first character, you can use the digits 0 through 9 and underscores in variable names.
The equal sign (=) is used to assign value to a variable. This is in stark contrast to the double equals (==) that are used to test equality between two values. For instance:
var1 = 2 : This statement says, “The value of the variable named var2 is 2.”
var1 == 2 : This asks the question, “Does the value of the variable named var1 equal 2?”
Type Casting
In programming, a variable needs to be associated with a data type. The data type constrains, or limits, the kind of data stored by the variable. For instance, does the variable x below store a number
or a string of characters? How about the variable y? How do you think Python computes the result of the variable z in the third code example?
x = "234"
y = 432 z = x + y
In some programming languages, the variable x in the previous example would be assumed to be a string because of the quotation marks. Therefore, the expression x+ y would fail because you can’t add a string and a number together.
Strictly typed programming languages like C require that you declare not only a variable’s name, but also the type of data that it can hold. Python isn’t like that; it’s much more lax.
Yes indeed—Python is pretty forgiving, data type-wise. You can use the type function to check the data type that Python associated with a variable. Try the following:
type(x)
Python 3 supports the following native data types:
Boolean: Possible values are True or False.
Numbers: Integers (whole numbers); Floats (decimal or fractional numbers), or complex numbers.
Strings: Character sequences.
Bytes: Binary data such as images or other media files.
Lists: Ordered value sequences.
Tuples: Ordered values that are different from lists inasmuch as lists can change their values (mutable), but tuples cannot (immutable).
Sets: Unordered value sequences.
Dictionaries: Unordered key-value pairs.
You can use type-casting functions to manually convert data from one data type to another. This is useful when you want to ensure that Python receives variable data in a particular format.
For instance, try this:
vara = "100"
type(vara)
The result of the above code is that Python sees “100” as a string rather than as an integer. Does that result surprise you? It shouldn’t. When the Python interpreter saw data contained within quotes, it assumed you wanted to use the str (string) data type instead of int (integer). You can fix it, though, by converting the string you assigned to the variable to an integer:
varb = int(vara) type(varb)
In other words, Python infers a data type based upon how you type. If you use quotes, then dollars to donuts Python assumes you’re talking about a string value. If you supply a number without quotes, then Python selects one of the numeric data types depending upon the number.
For instance, a variable value of 100 is an integer, and 100.1 is a float. Understand?
Concatenation
In Python, string concatenation enables you to patch together bits of code. To do this, simply use the plus sign (+). Consider the following examples, all of which you can try out in the Python Shell:
str1, str2 = "abc", "def": Two things—you can create and initialize more than one variable in one shot, and you can use single or double quotes to contain string data.
str1 + str2: Note that when you concatenate strings, no extra space is included. The result of this operation is abcdef.
str1 + " " + str2: You can pad spaces by passing in the space character(s) as a separate string literal. In this example, the result is “abc def”. Pretty cool, huh?
print("The combined string value is: " + str1 + str2): You can concatenate string literal data with variable data to provide the user with customized output.
Modules
In Python, modules are .py script files that contain one or more related code blocks. What is so cool about modules is that they make programming much more modular. Think of it: Would you rather write (or copy/paste) a bunch of functions you created that pertain to several different Python programs you’re working on, or would you rather have those functions stored in a module that you can load and unload at your convenience?
Earlier in this chapter I briefly introduced the random module that ships with the so-called reference version of Python 3. As you can see in Figure 11.3, the contents of the module are stored in plain text and can be viewed and analyzed by anyone.
FIGURE 11.3 Python modules are note encrypted, but boy, are they useful! Here you can see the code behind the randint function used earlier in the chapter.
Note: Where Are Modules Located?
You can run help(“modules”) to get a list of all currently available modules in your current Python 3 installation. After you get the name of your desired module, type help(“module_name”) to get the file location. For instance, in Raspbian, the random module is located by default in /usr/lib/python3.2/random.py.
Assuming a module is present on your system (see the note “Where Are Modules Located?” for more info), you can use the import statement to bring a module into the current Python environment. Note that an import statement lasts only for the duration of the current script file.
When you perform an import, all of the code contained in the module becomes available to you in Python. For instance, to import all code from the math module, you can issue any of the following statements:
Click here to view code image
import math from math import *
import math, random (we can import more than one module at a time; just use a comma separator)
After you’ve imported a module, run dir(module_name) to get a list of all the names (the Python term for code components) that are contained inside the module. To illustrate, run the following three content. As an example, let’s work with the sqrt function from the math module:
import math math.sqrt(25)
With respect to Python programming, a fully qualified function name takes the form of module.function. Thus, after importing the math module, you issue math.sqrt() when you want to run the sqrt() function that is contained in the math module.
Even though you imported the math module, the Python interpreter would get confused and issue an error if you used just sqrt() in your code without qualifying its location.
Note: Where to Find Cool Modules?
I’ve found that you can learn about any Python 3 module directly from the Python website. Check out the Python Module Index (http://is.gd/yr7n0A) to learn about the built-in module library. For third-party modules, see the Useful Modules list (http://is.gd/OvwCJm) at the Python Wiki. Finally, I cover Raspberry Pi-specific modules as we move through the remainder of this book.
As I said earlier, many Raspberry Pi projects require that you obtain and install additional modules.
You can use the Linux apt-get command in many cases.
One word of warning: You need to be mindful of the fact that you’re working with Python 3 and not Python 2. Many online tutorials show you how to do stuff with Python on the Pi, and the module and code references the older version of Python.
Let’s make sure you have the most recent version of the GPIO module in your Python 3 installation.
This module is important later because, you’ll recall, the GPIO headers are the principal way that you connect the Raspberry Pi to external hardware.
I’ve found that the case-sensitivity in Linux has caused Raspberry Pi users to conclude that their Python 3 installation is missing certain modules when, in point of fact, they are present. Try the
following procedure.
Task: Loading and then Updating the GPIO Module in Python 3
Many of the projects that I cover in the latter part of this book involve taking control of the Raspberry Pi’s General Purpose Input/Output (GPIO) header pins. Accordingly, it is crucial that you ensure that your Python installation has access to the GPIO modules.
1. From LXTerminal, type python3 to start an interactive Python 3 session.
2. Import the GPIO module included in Raspbian so you can begin the process of interacting with the Pi’s GPIO headers:
import RPI.GPIO
3. Did that work? No? Well, something you should know is that GPIO is a function library inside of the RPi module. Notice the mixed case. Try this:
import RPi.GPIO as GPIO
The as keyword is used to provide an alias to an imported module. This means you can call GPIO functions by using GPIO instead of RPi.GPIO. You had some more problems though, correct? It turns out you also need to run Python as root. Sheesh!
4. Run exit() to leave the interpreter and then issue sudo python3 to enter the interpreter as root. One more time with feeling!
import RPi.GPIO as GPIO dir(GPIO)
Now we’re cooking! The output is displayed in Figure 11.4.
FIGURE 11.4 Working with modules in Python 3 can be...interesting.
5. Exit the interpreter one final time. Let’s update the module to make sure you have the latest and greatest version:
Click here to view code image
sudo apt-get update sudo apt-get dist-upgrade
sudo apt-get install python3-rpi.gpio