Hacking Raspberry Pi (2014)
Part II. Software Foundations
Chapter 10. Programming Raspberry Pi with Python-Beginnings
If you emerged from Chapters 7 and 8 relatively unscathed, you are ready to embark on a more comprehensive programming adventure.
Scratch is a lot of fun to program, but the environment hides all of the programming complexity; this is by design, as previously discussed. Many educators consider Python to be an ideal first “true” programming language for the following reasons:
Python’s syntax and data typing are relatively intuitive and fairly forgiving of rookie mistakes.
Python is heavily documented; you can find easy-to-follow tutorials just about anywhere.
Python’s interactive interpreter makes learning new stuff fast and fun.
Python offers an amazing number of importable code libraries that give beginning programmers tools to build any kind of application.
Python is called a “general-purpose, high-level programming language” whose overarching design principle is code readability. In fact, you would be well-advised to read what Python fans consider to be their fundamental, guiding principles: the Zen of Python (http://is.gd/sXV6IU). Let me share with you my favorite entries from the Zen document:
Explicit is better than implicit.
Simple is better than complex.
For three simple sentences, that’s quite a bit of wisdom, right? As a programmer, you are much better off writing code that is as straightforward as possible and documented in such a way that any other Python programmer can read your code and instantly understand how your program works. To be sure, if you’ve been practicing with Scratch, you already understand how important community support is when you’re developing software projects.
Python’s focus on clarity and readability probably weighed heavily into the Raspberry Pi Foundation’s decision to build the Raspberry Pi development platform around Python. If you ever saw C or C++ code, you will instantly appreciate how much more approachable Python is on almost every level.
Note: Where It Began
Just a tad bit of history before we dive in: The Python programming language was invented by the Dutch programmer Guido van Rossum in the late 1980s. Rossum needed a fast, intuitive scripting language to help him automate administrative tasks, and he wasn’t getting very far with the tools he had in front of him at the time. Thus, Guido adapted the ABC programming language that was popular in the Netherlands at that time to a new language that focused on simplicity and readability without sacrificing power—enter Python!
What’s so cool about Python is its flexibility—some call Python a scripting language because you can write and test code quickly without the need for binary compilation. On the other hand, because Python has grown into a robust language that supports enterprise-level concepts such as object orientation, the term high-level programming language seems more appropriate for Python.
The way I want to teach you Python in this chapter and the next one (itself a hugely daunting task), is to jump right in and get your hands dirty with the environment. At the end of this chapter I give you some hand-selected online and print resources with which you can take the next steps in your development as a Python programmer.
To that point, however, I strongly encourage you to pick up Sams Teach Yourself Python Programming for Raspberry Pi, written by my Pearson colleagues Richard Blum and Christine Bresnahan. Their book touches briefly on the material we deep-dive into (the innards of the Pi), while my book does the same thing with regard to Python programming. I think that Richard and Christine’s book and my book complement each other quite nicely, thank you very much!
Let’s get to work.
Checking Out the Python Environment
Boot up your Pi and fire up a Terminal prompt. It doesn’t matter whether you are in LXDE or not at this point, although you’ll need LXDE in time when we discuss IDLE.
As it happens, there are two versions of Python currently in use today, and both of them are included in the Raspbian Linux distribution. In this book I choose to stick with Python 3, the current version, because it is a nice improvement over Python 2 (for those interested in an exhaustive comparison, visit the Python website at http://is.gd/kYsc97).
Try out the following commands, pressing Enter in between:
What you just did was to check the currently installed versions of Python 2 (the executable program file is python) and Python 3 (executable program file name of python3). As with all things in Linux, case is sensitive, so you need to supply the -V parameter and not -v to see the Python version.
Later in the book, you’ll find a lot of the code you need to undertake certain Raspberry Pi projects was written in Python 2. Don’t be alarmed! For our purposes, the differences between Python 3 and Python 2 are under the hood and everything you learn in this chapter and the next one is directly applicable to the Python 2 work you’ll do later on.
Now pop into LXDE and look at the two icons labeled IDLE and IDLE 3. These are shortcuts that open the Integrated DeveLopment Environment, or IDLE (pronounced eye-duhl), for Python 2 and Python 3, respectively. Try double-clicking IDLE 3; the interface can be found in Figure 10.1.
FIGURE 10.1 The IDLE development environment for Python 3.
What’s cool about IDLE, also called the Python Shell, is that it is itself a Python application that leveraged the Tkinter (pronounced tee kay inter) GUI toolkit. Tkinter and packages like it enable you to build graphical Python applications that leverage windows, colors, icons, buttons, and mouse navigation. That said, we’re focusing on console (command-line) applications in this book because Python graphical programming is an advanced topic and warrants its own chapter if not its own book.
An Integrated Development Environment, or IDE, is useful to a programmer because most IDEs offer time-shaving functionality such as the following:
Interactive help with programming language syntax
The ability to step into programs and stop/restart at predefined points
Detailed insight into design-time and run-time errors
IDLE offers all of this and more. It’s definitely not the most robust (or even stable) IDE, but I use it here because it comes standard with Python, and it’s already loaded in Raspbian.
Note: Python IDE Alternatives
If you discover that you love Python and want to try out alternatives to IDLE, be sure to check out some of the open source and commercial code editors and full-fledged IDEs that are out there. Some notable examples include Eclipse IDE (http://is.gd/fGo9FH) with the PyDev extension (http://is.gd/yDXZ8m), Komodo IDE (http://is.gd/bIPFT9), and WingIDE (http://is.gd/jyg8ig).
Enough about IDLE. The whole of Chapter 11, “Programming Raspberry Pi with Python—Next Steps,” is dedicated to building Python programs using IDLE. For the remainder of this chapter, we’ll stay in the Terminal environment to interact with Python 3.
Interacting with the Python 3 Interpreter
Open up a Terminal session on your Pi and try out the following procedure. Be sure to press Enter after issuing each command.
In the first line of code, you invoked the Python 3 interpreter. This means that until you either close the Terminal window or issue the exit() command, everything you type is sent directly to Python on your Pi.
In other words, when you send a Python statement to the interpreter, Python parses, or interprets, that line of code, performs the instruction(s) contained in the code, and presents the results as appropriate on the screen.
Thus, Python is called an interpreted programming language because it takes your plaintext code input and processes it directly into machine language. (Technically, Python busts the plaintext code into an intermediate state called byte code, but we don’t need to get too picky about it at this point.)
By contrast, compiled programming languages such as C and Microsoft .NET must be converted into executable binary machine language prior to their being run. Therefore, developing compiled-language projects takes much longer than creating interpreted-language ones because the compilation process can sometimes be tedious and time-intensive.
As I said earlier in this chapter, interpreted programming languages are oftentimes called scripting languages because of their agility and speed at which they can go from design time to run time.
Exiting the Interpreter
You can tell at a glance that you are inside the Python interactive interpreter because the command prompt displays as three right angle brackets (>>>). If you need to exit the interpreter to return to the command prompt, issue the following command:
To return to the interpreter, you know the drill: Type python3 and press Enter.
Getting Online Help
The help system that is built into the Python interpreter is, well, passable, although in my opinion you can’t beat the Python Documentation website (http://is.gd/SGejBj; keep it bookmarked!). Nevertheless, to access the online help, issue the following command from within the Python interactive interpreter:
To get a list of help topics, type topics. If you want a list of Python keywords, type keywords (see Figure 10.2).
FIGURE 10.2 The Python interpreter online help is decent enough.
You can get help regarding a particular keyword by typing that keyword (try print, for instance) from within the online help system. Alternatively, you can jump directly to a specific help page by issuing help(‘print’) from outside the help system but inside the Python interpreter.
Either way, after you are inside a help page and are ready to exit, type q (no, this is not intuitive). To add insult to injury, you must remember to press Ctrl+D to exit the online help system and return to the interpreter. Now who said that Python was intuitive again?
Writing Your First Python Program
The traditional first example when a student learns a new programming language is to have the program print “Hello World” on the screen. The remainder of this chapter is in keeping with that tradition.
From the Python interactive interpreter, issue the following command:
Congratulations on creating your first Python program! What you did in a single line of code is to instruct Python to output the string “Hello,World!” to the screen. Specifically, print is what’s called a function—a function is a named object that performs some action when the function is invoked.
Functions typically take one or more input parameters; these are fed to the function inside of parenthesis. Hence, in our Hello World example, Python fed our “Hello, World!” string as an input parameter to the print function, which in turn was written to echo its parameter to whatever output you specify (the screen, also called standard output or stdout, is used in the absence of a specific output value).
Issuing Python statements from the interactive interpreter is all well and good, but it is not sustainable for anything outside of the smallest of tasks and for testing/diagnostic purposes. To preserve your hard development work, you need to save your Python source code in a script file.
Historically, Python script files use the file extension .py. Under the hood, however, these are plaintext files that are creatable and readable in any text editor. Today we’ll use (you guessed it)...nano.
Task: Creating Your First Python Script
1. From a Terminal session, ensure that your present working directory is your home directory:
2. Create a new, blank text file in your home directory using nano as your editor:
3. Add the following code (which you can also see in Figure 10.3):
1: #!/usr/bin/env python
2: fn = input("What is your first name? ")
3: print("Hi there," , fn, "\n”)
FIGURE 10.3 Your first Python script.
Let’s cover what each line in the script means:
1: This is called the shebang line, and it simply instructs Linux as to where to find the Python executable program file. This is useful so you can invoke the Python interpreter from whatever present working directory you may be in at a given time.
2: This creates a variable named fn that stores the user’s response to the question string “What is your first name?” A variable is simply a temporary, in-memory placeholder for data. Because Python is a dynamically typed language, you don’t have to specify the data type for our new variable; the interpreter sees that you are obtaining string data and formats the variable accordingly.
The input function is used to solicit feedback from the user. The input parameter is simply the prompt string. Notice that I added an extra space after the question mark and before the closing quotes—this is to make the question and the user’s response more legible.
3: This command invokes the print function to present a dynamic string to the user. Use the comma inside the print function arguments to concatenate, or combine, multiple strings. Note that in this example the line concatenates three discrete elements:
The static string “Hi there,”
The current value of the fn variable
A newline character
Escape sequences are used in Python to send internal commands to the Python interpreter. The \n escape character (all escape characters begin with the backslash, by the way) tells Python to insert a new line at that point.
4. In nano, press Ctrl+X, Y, and Enter to save your work and exit the editor. Now it’s time to run the new script.
Note: The Most Common nano Keyboard Shortcuts
As you gain more experience with Linux and its myriad text editors, you may (like myself) choose nano as your preferred tool. To that end, you should memorize the following keyboard shortcuts: Ctrl+O (the letter, not zero) to save. Ctrl+V to jump to the next page. Ctrl+Y to return to the previous page. Ctrl+W to perform a keyword search. Finally, there is Ctrl+X to exit.
Running Python Scripts
In Raspbian, the path to the Python interpreter is included in the OS program search path. Therefore, you can invoke Python 3 from wherever you are in the command-line environment. However, you do need to be aware of where your target script is located.
Task: Running Python Scripts (command line)
When we’re experimenting with the Raspberry Pi in projects that are presented later in the book, you’ll be running several scripts. Therefore, learning how to execute Python scripts from the command line is a useful skill for any tech enthusiast, much less a student of the Raspberry Pi. Let’s begin!
1. Issue pwd to check your present working directory. If you aren’t in your home folder, issue cd ~.
2. To run a .py Python script that exists in the current directory (like your new script should be), run the following command:
3. How did your program run—pretty well? Good. Let’s now change to a different directory:
4. Try running the command in step 2 again. Were you successful? No? Now try the following:
Cool. At this point you should have a pretty good feel for how to run Python scripts from the command line.
Task: Running Python Scripts (IDLE)
I know that I said earlier that we focus on the IDLE environment in the next chapter, however, as long as I’m already on the subject it makes sense that I cover running scripts in IDLE now.
1. From the Raspbian LXDE desktop, double-click IDLE3 to open the Python 3 editor.
Note: Version Control, Re-Revisited
Remember that I’m using Python 3 in this book, so make sure you open IDLE 3 and not IDLE. You’ll immediately know you’ve invoked the incorrect Python version because you’ll see errors related to the print function, which underwent a change from a simple statement to a formal function between Python 2 and Python 3.
2. In the Python Shell window, click File, Open.
3. Use the controls in the Open dialog box to select the target .py script file. I show you this interface, which should be immediately understandable to OS X and Windows users, in Figure 10.4.
FIGURE 10.4 IDLE behaves like most GUI editor programs.
4. You’ll see your script show up in a separate IDLE editor window. To actually run the script, simply click Run, Run Module or press F5.
Broadening Your Python Horizons
Many programmers, myself included, learn a great deal concerning best and worst practices by studying the code of other developers. To that end, I want to share with you some rich sources of example Python scripts you should download to your Pi, run, and analyze.
For instance, here are links to some excellent Python sample code repositories that ought to give you plenty of experience and fun:
Code Like a Pythonista: http://is.gd/fE2Owx
Dive into Python 3: http://is.gd/3tP9ZL
I want to give a shout-out to Professor Anne Dawson of Coquitlam College in Canada: She put together an excellent list of Python 3 example programs at http://is.gd/Ipv80w. You’ll note that the file is a plaintext text file, which means you can easily copy and paste her code snippets into your own environment without carrying any extra HTML formatting baggage.
There are, however, a number of Python community websites that are static, and every budding Python programmer should have them bookmarked and review them frequently. Here are my own hand-picked selections:
http://is.gd/Pf9vb4: CPython is the standard Python distribution.
http://is.gd/SGejBj: Python 3 official documentation.
http://is.gd/EWR7d3: Python Enhancement Proposal (PEP) Index—PEPs are documents that define the formal Python specifications and best practices.
http://is.gd/sXV6IU: PEP 20 is called “The Zen of Python” and is required reading for any aspiring Python programmer.
http://is.gd/nCexcw: PEP 8 is titled “Style Guide for Python Code.” You’ll find this reference to be increasingly useful as you gain experience with Python programming.
http://is.gd/nNYCUy: Learning Python by Rick Lutz is, in my humble opinion, the best Python beginner’s book on the market.
So what do you think of Python as compared to Scratch? Are you able to see how Scratch projects are directly analogous to Python programs, albeit with greater simplicity?
At base, all computer programs behave the same way as computers: they accept instructions as input, perform some processing on that data, and then produce output to the user.
Moreover, all computer languages, no matter how rudimentary or cryptic their syntax rules, do the same kinds of stuff: the concepts of variables, procedures, loops, debugging, interpretation, compiling, and execution are the same no matter what specific language you feel most comfortable with.
In the next chapter, I help you broaden and deepen your understanding of Python even more. I know I’ve repeated the point ad nauseam, but you’ll thank me for focusing on Python so much here once you start building Raspberry Pi projects.