You are previewing Sams Teach Yourself Python Programming for Raspberry Pi in 24 Hours, Second Edition.
O'Reilly logo
Sams Teach Yourself Python Programming for Raspberry Pi in 24 Hours, Second Edition

Book Description

Python Programming for Raspberry Pi®

In just 24 sessions of one hour or less, Sams Teach Yourself Python Programming for Raspberry Pi in 24 Hours teaches you Python programming on Raspberry Pi, so you can start creating awesome projects for home automation, home theater, gaming, and more. Using this book’s straight-forward, step-by-step approach, you’ll move from the absolute basics all the way through network and web connections, multimedia, and even connecting with electronic circuits for sensing and robotics. Every lesson and case study application builds on what you’ve already learned, giving you a rock-solid foundation for real-world success!

  • Step-by-step instructions carefully walk you through the most common Raspberry Pi Python programming tasks.

  • Quizzes at the end of each chapter help you test your knowledge.

  • By the Way notes present interesting information related to the discussion.

  • Did You Know? tips offer advice or show you easier ways to perform tasks.

  • Watch Out! cautions alert you to possible problems and give you advice on how to avoid them.

  • Richard Blum has administered systems and networks for more than 25 years. He has published numerous Linux and open source books, and is an online instructor for web programming and Linux courses used by colleges across the United States. His books include Ubuntu Linux Secrets; Linux for Dummies, Ninth Edition; PostgreSQL 8 for Windows; and Professional Linux Programming.

    Christine Bresnahan began working as a systems administrator more than 25 years ago. Now an Adjunct Professor at Ivy Tech Community College, she teaches Python programming, Linux administration and computer security. She is coauthor of The Linux Bible, Eighth Edition. With Blum, she also coauthored Linux Command Line & Shell Scripting Bible, Second Edition.

  • Get your Raspberry Pi and choose the right low-cost peripherals

  • Set up Raspian Linux and the Python programming environment

  • Learn Python basics, including arithmetic and structured commands

  • Master Python 3 lists, tuples, diction-aries, sets, strings, files, and modules

  • Reuse the same Python code in multiple locations with functions

  • Manipulate string data efficiently with regular expressions

  • Practice simple object-oriented programming techniques

  • Use exception handling to make your code more reliable

  • Program modern graphical user interfaces with Raspberry Pi and OpenGL

  • Create Raspberry Pi games with the PyGame library

  • Learn network, web, and database techniques you can also use in business software

  • Write Python scripts that send email

  • Interact with other devices through Raspberry Pi’s GPIO interface

  • Walk through example Raspberry Pi projects that inspire you to do even more

  • On the Web:

    Register your book at informit.com/title/9780672337642 for access to all code examples from the book, as well as update and corrections as they become available.

    Table of Contents

    1. About This E-Book
    2. Title Page
    3. Copyright Page
    4. Contents at a Glance
    5. Table of Contents
    6. About the Authors
    7. Dedication
    8. Acknowledgments
    9. We Want to Hear from You!
    10. Reader Services
    11. Introduction
      1. Programming with Python
      2. Who Should Read This Book?
      3. Conventions Used in This Book
    12. Part I: Python Programming on the Raspberry Pi
      1. Hour 1. Setting Up the Raspberry Pi
        1. Obtaining a Raspberry Pi
          1. Exploring the Raspberry Pi’s History
          2. Understanding How Python Relates to the Raspberry Pi
        2. Acquiring a Raspberry Pi
        3. Determining the Necessary Peripherals
          1. The microSD Card
          2. Power Supply
          3. Output Display
          4. Keyboard and Mouse
          5. Using a Network Cable or Wi-Fi Adapter
        4. Nice Additional Peripherals
          1. Choosing a Case
          2. Portable Power Supply
          3. Looking at a Self-Powered USB Hub
        5. Deciding How to Purchase Peripherals
        6. Getting Your Raspberry Pi Working
          1. Doing Your Research
          2. Exploring the Installation Software
          3. Downloading NOOBS
          4. Moving NOOBS
          5. Plugging In the Peripherals
        7. Troubleshooting Your Raspberry Pi
          1. Check Your Peripheral Cords
          2. Check Your microSD Card
          3. Check Your Copy of NOOBS
          4. Check Your Display
          5. Check Your Peripherals
        8. Summary
        9. Q&A
        10. Workshop
          1. Quiz
          2. Answers
      2. Hour 2. Understanding the Raspbian Linux Distribution
        1. Learning About Linux
        2. Interacting with the Raspbian Command Line
        3. Interacting with the Raspbian GUI
        4. The LXDE Graphical Interface
          1. The LXPanel
        5. Summary
        6. Q&A
        7. Workshop
          1. Quiz
          2. Answers
      3. Hour 3. Setting Up a Programming Environment
        1. Exploring Python
          1. A Little Python History
          2. Python v3 Versus Python v2
        2. Checking Your Python Environment
          1. Checking the Python Interpreter and Interactive Shell
          2. Checking the Python Development Environment
          3. Checking for a Text Editor
        3. Installing Python and Tools
          1. Checking the Keyboard
        4. Learning About the Python Interpreter
        5. Learning About the Python Interactive Shell
        6. Learning About the Python Development Environment
          1. The IDLE Development Environment Shell
        7. Creating and Running Python Scripts
          1. Running a Python Script in the Interactive Shell
          2. Running a Python Script in IDLE
          3. Using IDLE to Create a Python Script
          4. Using a Text Editor to Create a Python Script
        8. Knowing Which Tool to Use and When
        9. Summary
        10. Q&A
        11. Workshop
          1. Quiz
          2. Answers
    13. Part II: Python Fundamentals
      1. Hour 4. Understanding Python Basics
        1. Producing Python Script Output
          1. Exploring the print Function
          2. Using Characters as print Function Arguments
          3. Formatting Output with the print Function
          4. Controlling Output with Escape Sequences
          5. Now for Something Fun!
        2. Formatting Scripts for Readability
          1. Long Print Lines
          2. Creating Comments
        3. Understanding Python Variables
          1. Python Keywords
          2. Creating Python Variable Names
        4. Assigning Value to Python Variables
          1. Formatting Variable and String Output
          2. Avoiding Unassigned Variables
          3. Assigning Long String Values to Variables
          4. More Variable Assignments
          5. Reassigning Values to a Variable
        5. Learning About Python Data Types
        6. Allowing Python Script Input
        7. Summary
        8. Q&A
        9. Workshop
          1. Quiz
          2. Answers
      2. Hour 5. Using Arithmetic in Your Programs
        1. Working with Math Operators
          1. Python Math Operators
          2. Order of Operations
          3. Using Variables in Math Calculations
          4. Floating-Point Accuracy
          5. Displaying Numbers
          6. Operator Shortcuts
        2. Calculating with Fractions
          1. The Fraction Object
          2. Fraction Operations
        3. Using Complex Number Math
          1. Creating Complex Numbers
          2. Complex Number Operations
        4. Getting Fancy with the math Module
          1. Number Theory Functions
          2. Power and Logarithmic Functions
          3. Trigonometric Functions
          4. Hyperbolic Functions
          5. Statistical Math Functions
        5. Using the NumPy Math Libraries
          1. NumPy Data Types
          2. Creating NumPy Arrays
          3. Using NumPy Arrays
        6. Summary
        7. Q&A
        8. Workshop
          1. Quiz
          2. Answers
      3. Hour 6. Controlling Your Program
        1. Working with the if Statement
        2. Grouping Multiple Statements
        3. Adding Other Options with the else Statement
        4. Adding More Options Using the elif Statement
        5. Comparing Values in Python
          1. Numeric Comparisons
          2. String Comparisons
          3. Boolean Comparisons
          4. Evaluating Function Results
        6. Checking Complex Conditions
          1. Using Logic Operators
          2. Combining Condition Checks
        7. Negating a Condition Check
        8. Summary
        9. Q&A
        10. Workshop
          1. Quiz
          2. Answers
      4. Hour 7. Learning About Loops
        1. Performing Repetitive Tasks
        2. Using the for Loop for Iteration
          1. Iterating Using Numeric Values in a List
          2. Watching for a Few “Gotchas”
          3. Assigning Data Types from a List
          4. Iterating Using Character Strings in a List
          5. Iterating Using a Variable
          6. Iterating Using the range Function
        3. Using the while Loop for Iteration
          1. Iterating Using Numeric Conditions
          2. Iterating Using String Conditions
          3. Using while True
        4. Creating Nested Loops
        5. Summary
        6. Q&A
        7. Workshop
          1. Quiz
          2. Answers
    14. Part III: Advanced Python
      1. Hour 8. Using Lists and Tuples
        1. Introducing Tuples
          1. Creating Tuples
          2. Accessing Data in Tuples
          3. Accessing a Range of Values
          4. Working with Tuples
        2. Introducing Lists
          1. Creating a List
          2. Extracting Data from a List
          3. Working with Lists
        3. Using Multidimensional Lists to Store Data
        4. Working with Lists and Tuples in Your Scripts
          1. Iterating Through a List or Tuple
          2. Sorting and Reversing Revisited
        5. Creating Lists by Using List Comprehensions
        6. Working with Ranges
        7. Summary
        8. Q&A
        9. Workshop
          1. Quiz
          2. Answers
      2. Hour 9. Dictionaries and Sets
        1. Understanding Python Dictionary Terms
        2. Exploring Dictionary Basics
          1. Creating a Dictionary
          2. Populating a Dictionary
          3. Obtaining Data from a Dictionary
          4. Updating a Dictionary
          5. Managing a Dictionary
        3. Programming with Dictionaries
        4. Understanding Python Sets
        5. Exploring Set Basics
          1. Populating a Set
        6. Obtaining Information from a Set
          1. Set Membership
          2. Set Union
          3. Set Intersection
          4. Set Difference
          5. Symmetric Set Difference
          6. Traversing a Set
        7. Modifying a Set
        8. Programming with Sets
        9. Summary
        10. Q&A
        11. Workshop
          1. Quiz
          2. Answers
      3. Hour 10. Working with Strings
        1. The Basics of Using Strings
          1. String Formats
          2. Creating Strings
          3. Handling String Values
        2. Using Functions to Manipulate Strings
          1. Altering String Values
          2. Splitting Strings
          3. Joining Strings
          4. Testing Strings
          5. Searching Strings
        3. Formatting Strings for Output
          1. The format() Function
          2. Formatting Numbers
        4. Summary
        5. Q&A
        6. Workshop
          1. Quiz
          2. Answers
      4. Hour 11. Using Files
        1. Understanding Linux File Structures
          1. Looking at Linux Directories
        2. Managing Files and Directories via Python
        3. Opening a File
          1. Designating the Open Mode
          2. Using File Object Methods
        4. Reading a File
          1. Reading an Entire File
          2. Reading a File Line-by-Line
          3. Reading a File in a Nonsequential Manner
        5. Closing a File
        6. Writing to a File
          1. Creating and Writing to a New File
          2. Writing to a Preexisting File
        7. Summary
        8. Q&A
        9. Workshop
          1. Quiz
          2. Answers
      5. Hour 12. Creating Functions
        1. Utilizing Python Functions in Your Programs
          1. Creating a Function
          2. Using Functions
        2. Returning a Value
        3. Passing Values to Functions
          1. Passing Arguments
          2. Setting Default Parameter Values
          3. Dealing with a Variable Number of Arguments
          4. Retrieving Values Using Dictionaries
        4. Handling Variables in a Function
          1. Local Variables
          2. Global Variables
        5. Using Lists with Functions
        6. Using Recursion with Functions
        7. Summary
        8. Q&A
        9. Workshop
          1. Quiz
          2. Answers
      6. Hour 13. Working with Modules
        1. Introducing Module Concepts
        2. Exploring Standard Modules
        3. Learning About Python Modules
        4. Creating Custom Modules
          1. Creating or Gathering Functions That Go Together
          2. Determining a Module Name
          3. Creating the Custom Module in a Test Directory
          4. Testing the Custom Module
          5. Moving a Module to a Production Directory
          6. Checking the Path and Modifying It, If Needed
          7. Testing the Production Custom Module
        5. Summary
        6. Q&A
        7. Workshop
          1. Quiz
          2. Answers
      7. Hour 14. Exploring the World of Object-Oriented Programming
        1. Understanding the Basics of Object-Oriented Programming
          1. What Is OOP?
          2. Defining a Class
          3. Creating an Instance
          4. Default Attribute Values
        2. Defining Class Methods
          1. Mutator Methods
          2. Accessor Methods
          3. Adding Helper Methods to Your Code
        3. Sharing Your Code with Class Modules
        4. Summary
        5. Q&A
        6. Workshop
          1. Quiz
          2. Answers
      8. Hour 15. Employing Inheritance
        1. Learning About the Class Problem
        2. Understanding Subclasses and Inheritance
        3. Using Inheritance in Python
          1. Creating a Subclass
          2. Adding a Subclass to an Object Module File
          3. Adding Additional Subclasses
          4. Putting a Subclass in Its Own Object Module File
        4. Using Inheritance in Python Scripts
        5. Summary
        6. Q&A
        7. Workshop
          1. Quiz
          2. Answers
      9. Hour 16. Regular Expressions
        1. What Are Regular Expressions?
          1. Definition of Regular Expressions
          2. Types of Regular Expressions
        2. Working with Regular Expressions in Python
          1. Regular Expression Functions
        3. The match() Function
        4. The search() Function
        5. The findall() and finditer() Functions
          1. Compiled Regular Expressions
        6. Defining Basic Patterns
          1. Plain Text
          2. Special Characters
          3. Anchor Characters
          4. The Dot Character
          5. Character Classes
          6. Negating Character Classes
          7. Using Ranges
          8. The Asterisk
        7. Using Advanced Regular Expressions Features
          1. The Question Mark
          2. The Plus Sign
          3. Using Braces
          4. The Pipe Symbol
          5. Grouping Expressions
        8. Working with Regular Expressions in Your Python Scripts
        9. Summary
        10. Q&A
        11. Workshop
          1. Quiz
          2. Answers
      10. Hour 17. Exception Handling
        1. Understanding Exceptions
          1. Syntactical Error Exceptions
          2. Runtime Error Exceptions
        2. Handling Exceptions
        3. Handling Multiple Exceptions
          1. Creating Multiple try except Statement Blocks
          2. Handling Generic Exceptions
          3. Understanding try except Statement Options
        4. Summary
        5. Q&A
        6. Workshop
          1. Quiz
          2. Answers
    15. Part IV: Graphical Programming
      1. Hour 18. GUI Programming
        1. Programming for a GUI Environment
          1. The Window Interface
          2. Event-Driven Programming
        2. Examining Python GUI Packages
        3. Using the tkinter Package
          1. Creating a Window
          2. Adding Widgets to the Window
          3. Defining Event Handlers
        4. Exploring the tkinter Widgets
          1. Using the Label Widget
          2. Adding the Button Widget
          3. Working with the Checkbutton Widget
          4. Using the Entry Widget
          5. Adding a Text Widget
          6. Using a Listbox Widget
          7. Working with the Menu Widget
        5. Summary
        6. Q&A
        7. Workshop
          1. Quiz
          2. Answers
      2. Hour 19. Game Programming
        1. Understanding Game Programming
        2. Learning About Game Tools
        3. Setting Up the PyGame Library
          1. Checking for PyGame
        4. Using PyGame
          1. Loading and Initializing PyGame
          2. Setting Up the Game Screen
          3. Putting Text on the Game Screen
        5. Learning More About PyGame
          1. Staying in the Game
          2. Drawing Images and Shapes
          3. Putting Sound into the Game
        6. Dealing with PyGame Action
          1. Moving Graphics Around the Game Screen
          2. Interacting with Graphics on the Game Screen
        7. Summary
        8. Q&A
        9. Workshop
          1. Quiz
          2. Answers
    16. Part V: Business Programming
      1. Hour 20. Using the Network
        1. Finding the Python Network Modules
        2. Working with Email Servers
          1. Email in the Linux World
          2. The smtplib Library
          3. Using the smtplib Library
        3. Working with Web Servers
          1. Retrieving Webpages
          2. Parsing Webpage Data
        4. Linking Programs Using Socket Programming
          1. What Is Socket Programming?
          2. The Python socket Module
          3. Creating the Server Program
          4. Creating the Client Program
          5. Running the Client/Server Demo
        5. Summary
        6. Q&A
        7. Workshop
          1. Quiz
          2. Answers
      2. Hour 21. Using Databases in Your Programming
        1. Working with the MySQL Database
          1. Installing MySQL
          2. Setting Up the MySQL Environment
          3. Installing the Python MySQL Module
          4. Creating Your Python Scripts
        2. Using the PostgreSQL Database
          1. Installing PostgreSQL
          2. Setting Up the PostgreSQL Environment
          3. Installing the Python PostgreSQL Module
          4. Coding with psycopg2
        3. Summary
        4. Q&A
        5. Workshop
          1. Quiz
          2. Answers
      3. Hour 22. Web Programming
        1. Running a Web Server on the Pi
          1. Installing the Apache Web Server
          2. Serving HTML Files
        2. Programming with the Common Gateway Interface
          1. What Is CGI?
          2. Running Python Programs
        3. Expanding Your Python Webpages
          1. Formatting Output
          2. Working with Dynamic Webpages
          3. Debugging Python Programs
        4. Processing Forms
          1. Creating Web Forms
          2. The cgi Module
        5. Summary
        6. Q&A
        7. Workshop
          1. Quiz
          2. Answers
    17. Part VI: Raspberry Pi Python Projects
      1. Hour 23. Creating Basic Pi/Python Projects
        1. Thinking About Basic Pi/Python Projects
        2. Displaying HD Images via Python
          1. Understanding High Definition
          2. Creating the Image Presentation Script
          3. Setting Up the Presentation Screen
          4. Finding the Images
          5. Storing Photos on a Removable Drive
          6. Scaling the Photos
          7. Centering the Photos
          8. Framing the Photos
          9. Improving the Presentation Speed
          10. Potential Script Modifications
        3. Playing Music
          1. Creating a Basic Music Script
          2. Storing Your Music on a Removable Disk
          3. Using a Music Playlist
          4. Controlling the Playback
          5. Making the Play List Random
          6. Creating a Special Presentation
        4. Summary
        5. Q&A
        6. Workshop
          1. Quiz
          2. Answers
      2. Hour 24. Working with Advanced Pi/Python Projects
        1. Exploring the GPIO Interface
          1. What Is the GPIO Interface?
          2. The GPIO Pin Layout
          3. Connecting to the GPIO
        2. Using the RPi.GPIO Module
          1. Installing RPi.GPIO
          2. Startup Methods
        3. Controlling GPIO Output
          1. Setting Up the Hardware to View the GPIO Output
          2. Testing the GPIO Output
          3. Blinking the LED
          4. Creating a Fancy Blinker
        4. Detecting GPIO Input
          1. Setting Up the Hardware for Detecting Input
          2. Working with Input Signals
          3. Input Polling
          4. Input Events
        5. Summary
        6. Q&A
        7. Workshop
          1. Quiz
          2. Answers
    18. Appendixes
      1. Appendix A. Loading the Raspbian Operating System onto an SD Card
        1. Downloading NOOBS
        2. Verifying NOOBS Checksum
          1. Checking a Checksum on Linux
          2. Checking a Checksum on Windows
          3. Checking a Checksum on OS X
        3. Unpacking the NOOBS Zip File
          1. Unpacking a Zip File on Linux
          2. Unpacking a Zip File on Windows
          3. Unpacking a Zip File on OS X
        4. Formatting the MicroSD Card
          1. Formatting a MicroSD Card on Linux
          2. Formatting a MicroSD Card on Windows
          3. Formatting a MicroSD Card on OS X
        5. Copying NOOBS to a MicroSD Card
      2. Appendix B. Raspberry Pi Models Synopsis
        1. Raspberry Pi 2 Model B
        2. Raspberry Pi 1 Model B+
        3. Raspberry Pi 1 Model A+
        4. Older Raspberry Pi Models
    19. Index
    20. Code Snippets