Beginning Python: From Novice to Professional, Second Edition

Book description

Gain a fundamental understanding of Python's syntax and features with the second edition of Beginning Python, an up–to–date introduction and practical reference. Covering a wide array of Python–related programming topics, including addressing language internals, database integration, network programming, and web services, you'll be guided by sound development principles. Ten accompanying projects will ensure you can get your hands dirty in no time.

Updated to reflect the latest in Python programming paradigms and several of the most crucial features found in Python 3.0 (otherwise known as Python 3000), advanced topics, such as extending Python and packaging/distributing Python applications, are also covered.

Table of contents

  1. Coverpage
  2. Titlepage
  3. Copyright
  4. Contents at a Glance
  5. Contents
  6. About the Author
  7. About the Technical Reviewer
  8. Preface
  9. Introduction
  10. Chapter 1 Instant Hacking: The Basics
    1. Installing Python
      1. Windows
      2. Linux and UNIX
      3. Macintosh
      4. Other Distributions
      5. Keeping in Touch and Up-to-Date
    2. The Interactive Interpreter
    3. Algo . . . What?
    4. Numbers and Expressions
      1. Large Integers
      2. Hexadecimals and Octals
    5. Variables
    6. Statements
    7. Getting Input from the User
    8. Functions
    9. Modules
      1. cmath and Complex Numbers
      2. Back to the __future__
    10. Saving and Executing Your Programs
      1. Running Your Python Scripts from a Command Prompt
      2. Making Your Scripts Behave Like Normal Programs
      3. Comments
    11. Strings
      1. Single-Quoted Strings and Escaping Quotes
      2. Concatenating Strings
      3. String Representations, str and repr
      4. input vs. raw_input
      5. Long Strings, Raw Strings, and Unicode
    12. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  11. Chapter 2 Lists and Tuples
    1. Sequence Overview
    2. Common Sequence Operations
      1. Indexing
      2. Slicing
      3. Adding Sequences
      4. Multiplication
      5. Membership
      6. Length, Minimum, and Maximum
    3. Lists: Python’s Workhorse
      1. The list Function
      2. Basic List Operations
      3. List Methods
    4. Tuples: Immutable Sequences
      1. The tuple Function
      2. Basic Tuple Operations
      3. So What’s the Point?
    5. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  12. Chapter 3 Working with Strings
    1. Basic String Operations
    2. String Formatting: The Short Version
    3. String Formatting: The Long Version
      1. Simple Conversion
      2. Width and Precision
      3. Signs, Alignment, and Zero-Padding
    4. String Methods
      1. find
      2. join
      3. lower
      4. replace
      5. split
      6. strip
      7. translate
    5. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  13. Chapter 4 Dictionaries: When Indices Won’t Do
    1. Dictionary Uses
    2. Creating and Using Dictionaries
      1. The dict Function
      2. Basic Dictionary Operations
      3. String Formatting with Dictionaries
      4. Dictionary Methods
    3. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  14. Chapter 5 Conditionals, Loops, and Some Other Statements
    1. More About print and import
      1. Printing with Commas
      2. Importing Something As Something Else
    2. Assignment Magic
      1. Sequence Unpacking
      2. Chained Assignments
      3. Augmented Assignments
    3. Blocks: The Joy of Indentation
    4. Conditions and Conditional Statements
      1. So That’s What Those Boolean Values Are For
      2. Conditional Execution and the if Statement
      3. else Clauses
      4. elif Clauses
      5. Nesting Blocks
      6. More Complex Conditions
      7. Assertions
    5. Loops
      1. while Loops
      2. for Loops
      3. Iterating Over Dictionaries
      4. Some Iteration Utilities
      5. Breaking Out of Loops
      6. else Clauses in Loops
    6. List Comprehension—Slightly Loopy
    7. And Three for the Road
      1. Nothing Happened!
      2. Deleting with del
      3. Executing and Evaluating Strings with exec and eval
    8. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  15. Chapter 6 Abstraction
    1. Laziness Is a Virtue
    2. Abstraction and Structure
    3. Creating Your Own Functions
      1. Documenting Functions
      2. Functions That Aren’t Really Functions
    4. The Magic of Parameters
      1. Where Do the Values Come From?
      2. Can I Change a Parameter?
      3. Keyword Parameters and Defaults
      4. Collecting Parameters
      5. Reversing the Process
      6. Parameter Practice
    5. Scoping
    6. Recursion
      1. Two Classics: Factorial and Power
      2. Another Classic: Binary Search
    7. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  16. Chapter 7 More Abstraction
    1. The Magic of Objects
      1. Polymorphism
      2. Encapsulation
      3. Inheritance
    2. Classes and Types
      1. What Is a Class, Exactly?
      2. Making Your Own Classes
      3. Attributes, Functions, and Methods
      4. Privacy Revisited
      5. The Class Namespace
      6. Specifying a Superclass
      7. Investigating Inheritance
      8. Multiple Superclasses
      9. Interfaces and Introspection
    3. Some Thoughts on Object-Oriented Design
    4. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  17. Chapter 8 Exceptions
    1. What Is an Exception?
    2. Making Things Go Wrong . . . Your Way
      1. The raise Statement
      2. Custom Exception Classes
    3. Catching Exceptions
      1. Look, Ma, No Arguments!
      2. More Than One except Clause
      3. Catching Two Exceptions with One Block
      4. Catching the Object
      5. A Real Catchall
      6. When All Is Well
      7. And Finally
    4. Exceptions and Functions
    5. The Zen of Exceptions
    6. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  18. Chapter 9 Magic Methods, Properties, and Iterators
    1. Before We Begin
    2. Constructors
      1. Overriding Methods in General, and the Constructor in Particular
      2. Calling the Unbound Superclass Constructor
      3. Using the super Function
    3. Item Access
      1. The Basic Sequence and Mapping Protocol
      2. Subclassing list, dict, and str
    4. More Magic
    5. Properties
      1. The property Function
      2. Static Methods and Class Methods
      3. __getattr__, __setattr__, and Friends
    6. Iterators
      1. The Iterator Protocol
      2. Making Sequences from Iterators
    7. Generators
      1. Making a Generator
      2. A Recursive Generator
      3. Generators in General
      4. Generator Methods
      5. Simulating Generators
    8. The Eight Queens
      1. Generators and Backtracking
      2. The Problem
      3. State Representation
      4. Finding Conflicts
      5. The Base Case
      6. The Recursive Case
      7. Wrapping It Up
    9. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  19. Chapter 10 Batteries Included
    1. Modules
      1. Modules Are Programs
      2. Modules Are Used to Define Things
      3. Making Your Modules Available
      4. Packages
    2. Exploring Modules
      1. What’s in a Module?
      2. Getting Help with help
      3. Documentation
      4. Use the Source
    3. The Standard Library: A Few Favorites
      1. sys
      2. os
      3. fileinput
      4. Sets, Heaps, and Deques
      5. time
      6. random
      7. shelve
      8. re
      9. Other Interesting Standard Modules
    4. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  20. Chapter 11 Files and Stuff
    1. Opening Files
      1. File Modes
      2. Buffering
    2. The Basic File Methods
      1. Reading and Writing
      2. Piping Output
      3. Reading and Writing Lines
      4. Closing Files
      5. Using the Basic File Methods
    3. Iterating over File Contents
      1. Doing It Byte by Byte
      2. One Line at a Time
      3. Reading Everything
      4. Lazy Line Iteration with fileinput
      5. File Iterators
    4. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  21. Chapter 12 Graphical User Interfaces
    1. A Plethora of Platforms
    2. Downloading and Installing wxPython
    3. Building a Sample GUI Application
      1. Getting Started
      2. Windows and Components
      3. Labels, Titles, and Positions
      4. More Intelligent Layout
      5. Event Handling
      6. The Finished Program
    4. But I’d Rather Use
      1. Using Tkinter
      2. Using Jython and Swing
      3. Using Something Else
    5. A Quick Summary
      1. What Now?
  22. Chapter 13 Database Support
    1. The Python Database API
      1. Global Variables
      2. Exceptions
      3. Connections and Cursors
      4. Types
    2. SQLite and PySQLite
      1. Getting Started
      2. A Sample Database Application
    3. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  23. Chapter 14 Network Programming
    1. A Handful of Networking Modules
      1. The socket Module
      2. The urllib and urllib2 Modules
      3. Other Modules
    2. SocketServer and Friends
    3. Multiple Connections
      1. Forking and Threading with SocketServer
      2. Asynchronous I/O with select and poll
    4. Twisted
      1. Downloading and Installing Twisted
      2. Writing a Twisted Server
    5. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  24. Chapter 15 Python and the Web
    1. Screen Scraping
      1. Tidy and XHTML Parsing
      2. Beautiful Soup
    2. Dynamic Web Pages with CGI
      1. Step 1. Preparing the Web Server
      2. Step 2. Adding the Pound Bang Line
      3. Step 3. Setting the File Permissions
      4. CGI Security Risks
      5. A Simple CGI Script
      6. Debugging with cgitb
      7. Using the cgi Module
      8. A Simple Form
    3. One Step Up: mod_python
      1. Installing mod_python
      2. CGI Handler
      3. PSP
      4. The Publisher
    4. Web Application Frameworks
    5. Web Services: Scraping Done Right
      1. RSS and Friends
      2. Remote Procedure Calls with XML-RPC
      3. SOAP
    6. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  25. Chapter 16 Testing, 1-2-3
    1. Test First, Code Later
      1. Precise Requirement Specification
      2. Planning for Change
      3. The 1-2-3 (and 4) of Testing
    2. Tools for Testing
      1. doctest
      2. unittest
    3. Beyond Unit Tests
      1. Source Code Checking with PyChecker and PyLint
      2. Profiling
    4. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  26. Chapter 17 Extending Python
    1. The Best of Both Worlds
    2. The Really Easy Way: Jython and IronPython
    3. Writing C Extensions
      1. A Swig of . . . SWIG
      2. Hacking It on Your Own
    4. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  27. Chapter 18 Packaging Your Programs
    1. Distutils Basics
    2. Wrapping Things Up
      1. Building an Archive File
      2. Creating a Windows Installer or an RPM Package
    3. Compiling Extensions
    4. Creating Executable Programs with py2exe
    5. A Quick Summary
      1. New Functions in This Chapter
      2. What Now?
  28. Chapter 19 Playful Programming
    1. Why Playful?
    2. The Jujitsu of Programming
    3. Prototyping
    4. Configuration
      1. Extracting Constants
      2. Configuration Files
    5. Logging
    6. If You Can’t Be Bothered
    7. If You Want to Learn More
    8. A Quick Summary
      1. What Now?
  29. Chapter 20 Project 1: Instant Markup
    1. What’s the Problem?
    2. Useful Tools
    3. Preparations
    4. First Implementation
      1. Finding Blocks of Text
      2. Adding Some Markup
    5. Second Implementation
      1. Handlers
      2. A Handler Superclass
      3. Rules
      4. A Rule Superclass
      5. Filters
      6. The Parser
      7. Constructing the Rules and Filters
      8. Putting It All Together
    6. Further Exploration
      1. What Now?
  30. Chapter 21 Project 2: Painting a Pretty Picture
    1. What’s the Problem?
    2. Useful Tools
    3. Preparations
    4. First Implementation
      1. Drawing with ReportLab
      2. Constructing Some PolyLines
      3. Writing the Prototype
    5. Second Implementation
      1. Getting the Data
      2. Using the LinePlot Class
    6. Further Exploration
      1. What Now?
  31. Chapter 22 Project 3: XML for All Occasions
    1. What’s the Problem?
    2. Useful Tools
    3. Preparations
    4. First Implementation
      1. Creating a Simple Content Handler
      2. Creating HTML Pages
    5. Second Implementation
      1. A Dispatcher Mix-In Class
      2. Factoring Out the Header, Footer, and Default Handling
      3. Support for Directories
      4. The Event Handlers
    6. Further Exploration
      1. What Now?
  32. Chapter 23 Project 4: In the News
    1. What’s the Problem?
    2. Useful Tools
    3. Preparations
    4. First Implementation
    5. Second Implementation
    6. Further Exploration
      1. What Now?
  33. Chapter 24 Project 5: A Virtual Tea Party
    1. What’s the Problem?
    2. Useful Tools
    3. Preparations
    4. First Implementation
      1. The ChatServer Class
      2. The ChatSession Class
      3. Putting It Together
    5. Second Implementation
      1. Basic Command Interpretation
      2. Rooms
      3. Login and Logout Rooms
      4. The Main Chat Room
      5. The New Server
    6. Further Exploration
      1. What Now?
  34. Chapter 25 Project 6: Remote Editing with CGI
    1. What’s the Problem?
    2. Useful Tools
    3. Preparations
    4. First Implementation
    5. Second Implementation
      1. Creating the File Name Form
      2. Writing the Editor Script
      3. Writing the Save Script
      4. Running the Editor
    6. Further Exploration
      1. What Now?
  35. Chapter 26 Project 7: Your Own Bulletin Board
    1. What’s the Problem?
    2. Useful Tools
    3. Preparations
    4. First Implementation
    5. Second Implementation
      1. Writing the Main Script
      2. Writing the View Script
      3. Writing the Edit Script
      4. Writing the Save Script
      5. Trying It Out
    6. Further Exploration
      1. What Now?
  36. Chapter 27 Project 8: File Sharing with XML-RPC
    1. What’s the Problem?
    2. Useful Tools
    3. Preparations
    4. First Implementation
      1. Implementing a Simple Node
      2. Trying Out the First Implementation
    5. Second Implementation
      1. Creating the Client Interface
      2. Raising Exceptions
      3. Validating File Names
      4. Trying Out the Second Implementation
    6. Further Exploration
      1. What Now?
  37. Chapter 28 Project 9: File Sharing II—Now with GUI!
    1. What’s the Problem?
    2. Useful Tools
    3. Preparations
    4. First Implementation
    5. Second Implementation
    6. Further Exploration
      1. What Now?
  38. Chapter 29 Project 10: Do-It-Yourself Arcade Game
    1. What’s the Problem?
    2. Useful Tools
      1. pygame
      2. pygame.locals
      3. pygame.display
      4. pygame.font
      5. pygame.sprite
      6. pygame.mouse
      7. pygame.event
      8. pygame.image
    3. Preparations
    4. First Implementation
    5. Second Implementation
    6. Further Exploration
      1. What Now?
  39. Appendix A The Short Version
    1. The Basics
    2. Functions
    3. Objects and Stuff
    4. Some Loose Ends
  40. Appendix B Python Reference
    1. Expressions
    2. Statements
      1. Simple Statements
      2. Compound Statements
  41. Appendix C Online Resources
    1. Python Distributions
    2. Python Documentation
    3. Useful Toolkits and Modules
    4. Newsgroups, Mailing Lists, and Blogs
  42. Appendix D Python 3.0
    1. Strings and I/O
      1. Strings, Bytes, and Encodings
      2. Console I/O
      3. New String Formatting
    2. Classes and Functions
      1. Function Annotation
      2. Abstract Base Classes
      3. Class Decorators and New Metaclass Syntax
      4. Keyword-Only Parameters
      5. Nonlocal Variables
    3. Iterables, Comprehensions, and Views
      1. Extended Iterable Unpacking
      2. Dictionary and Set Comprehension
      3. Dictionary Views
      4. Iterator Return Values
    4. Things That Have Gone
    5. Some Minor Issues
    6. The Standard Library
    7. Other Stuff
  43. Index

Product information

  • Title: Beginning Python: From Novice to Professional, Second Edition
  • Author(s): Magnus Lie Hetland
  • Release date: September 2008
  • Publisher(s): Apress
  • ISBN: 9781430206347