Learning Python

Book description

Learning Python is an introduction to the increasingly popular Python programming language. Python is an interpreted, interactive, object-oriented scripting language. Python is growing in popularity because:

  • It is available on all important platforms: Windows NT, Windows 95, Windows 98, Linux, all major UNIX platforms, MacOS, and even the BeOS.

  • It is open-source software, copyrighted but freely available for use, even in commercial applications.

  • Its clean object-oriented interface makes it a valuable prototyping tool for C++ programmers.

  • It works well with all popular windowing toolkits, including MFC, Tk, Mac, X11, and Motif. Learning Python is written by Mark Lutz, author of Programming Python and Python Pocket Reference; and David Ascher, a vision scientist and Python user. This book starts with a thorough introduction to the elements of Python: types, operators, statements, classes, functions, modules, and exceptions. By reading the first part of the book, the reader will be able to understand and construct programs in the Python language. In the second part of the book, the authors present more advanced information, demonstrating how Python performs common tasks and presenting real applications and the libraries available for those applications. All the examples use the Python interpreter, so the reader can type them in and get instant feedback. Each chapter ends with a series of exercises. Solutions to the exercises are in an appendix.

Table of contents

  1. Learning Python
    1. Preface
      1. About This Book
        1. This Book’s Scope
        2. This Book’s Style
          1. Part I
          2. Part II
          3. Part III
        3. Prerequisites
        4. Book Updates
      2. Font Conventions
      3. About the Programs in This Book
      4. How to Contact Us
      5. Acknowledgments
        1. Mark Also Says:
        2. David Also Says:
    2. I. The Core Language
      1. 1. Getting Started
        1. Why Python?
          1. An Executive Summary
            1. It’s object-oriented
            2. It’s free
            3. It’s portable
            4. It’s powerful
            5. It’s mixable
            6. It’s easy to use
            7. It’s easy to learn
          2. Python on the Job
            1. System utilities
            2. GUIs
            3. Component integration
            4. Rapid prototyping
            5. Internet scripting
            6. Numeric programming
            7. Database programming
            8. And more: Image processing, AI, distributed objects, etc.
          3. Python in Commercial Products
          4. Python Versus Similar Tools
        2. How to Run Python Programs
          1. The Interactive Command Line
          2. Running Module Files
          3. Running Unix-Style Scripts
          4. Embedded Code and Objects
          5. Platform-Specific Startup Methods
          6. What You Type and Where You Type It
        3. A First Look at Module Files
          1. A First Look at Namespace Inspection
        4. Python Configuration Details
          1. Environment Variables
          2. An Example Startup Script
          3. A GUI Test Session
          4. Installation Overview
        5. Summary
        6. Exercises
      2. 2. Types and Operators
        1. Python Program Structure
        2. Why Use Built-in Types?
        3. Numbers
          1. Standard Numeric Types
          2. Built-in Tools and Extensions
          3. Python Expression Operators
            1. Mixed operators: Operators bind tighter lower in the table
            2. Parentheses group subexpressions
            3. Mixed types: Converted up just as in C
            4. Preview: operator overloading
          4. Numbers in Action
            1. Basic operations
            2. B itwise operations
            3. L ong integers
            4. Complex numbers
            5. Other numeric tools
        4. Strings
          1. Strings in Action
            1. Basic operations
            2. Indexing and slicing
            3. C hanging and formatting
            4. Common string tools
            5. String constant variations
          2. Generic Type Concepts
            1. Types share operation sets by categories
            2. Mutable types can be changed in place
        5. Lists
          1. Lists in Action
            1. Basic operations
            2. In dexing and slicing
            3. Changing lists in place
        6. Dictionaries
          1. Dictionaries in Action
            1. Basic operations
            2. Changing dictionaries
            3. A marginally more real example
          2. Dictionary Usage Notes
        7. Tuples
          1. Why Lists and Tuples?
        8. Files
          1. Files in Action
          2. Related Python Tools
        9. General Object Properties
          1. Type Categories Revisited
          2. Generality
          3. Shared References
          4. Comparisons, Equality, and Truth
          5. Python’s Type Hierarchies
        10. Built-in Type Gotchas
          1. Assignment Creates References, Not Copies
            1. Solutions
          2. Repetition Adds One-Level Deep
            1. Solutions
          3. Cyclic Data Structures Can’t Be Printed
            1. Solutions
          4. Immutable Types Can’t Be Changed in Place
            1. Solutions
        11. Summary
        12. Exercises
      3. 3. Basic Statements
        1. Assignment
          1. Variable Name Rules
        2. Expressions
        3. Print
          1. The Python “Hello World” Program
        4. if Tests
          1. General Format
          2. Examples
          3. Python Syntax Rules
            1. B lock delimiters
            2. S tatement delimiters
            3. A few special cases
          4. Truth Tests Revisited
        5. while Loops
          1. General Format
          2. Examples
          3. break, continue, pass, and the Loop else
            1. General loop format
            2. Examples
        6. for Loops
          1. General Format
          2. Examples
          3. range and Counter Loops
            1. Examples
        7. Common Coding Gotchas
        8. Summary
        9. Exercises
      4. 4. Functions
        1. Why Use Functions?
        2. Function Basics
          1. General Form
          2. Definitions and Calls
          3. Example: Intersecting Sequences
            1. Definition
            2. Calls
        3. Scope Rules in Functions
          1. Name Resolution: The LGB Rule
          2. Example
          3. The global Statement
        4. Argument Passing
          1. More on return
          2. Special Argument-Matching Modes
            1. A first example
            2. A second example: Arbitrary-argument set functions
            3. The gritty details
        5. Odds and Ends
          1. lambda Expressions
          2. The apply Built-in
          3. The map Built-in
          4. Python “Procedures”
          5. Function Design Concepts
          6. Functions Are Objects: Indirect Calls
        6. Function Gotchas
          1. Local Names Are Detected Statically
            1. Solution
          2. Nested Functions Aren’t Nested Scopes
            1. Solution
          3. Using Defaults to Save References
          4. Defaults and Mutable Objects
            1. Solution
        7. Summary
        8. Exercises
      5. 5. Modules
        1. Why Use Modules?
        2. Module Basics
          1. Definition
          2. Usage
        3. Module Files Are Namespaces
          1. Name Qualification
        4. Import Model
          1. Imports Happen Only Once
          2. import and from Are Assignments
        5. Reloading Modules
          1. General Form
          2. Example
        6. Odds and Ends
          1. Module Compilation Model
          2. Data Hiding Is a Convention
          3. Mixed Modes: __name__ and __main__
          4. Changing the Module Search Path
          5. Module Packages (New in 1.5)
          6. Module Design Concepts
          7. Modules Are Objects: Metaprograms
        7. Module Gotchas
          1. Importing Modules by Name String
            1. Solution
          2. from Copies Names but Doesn’t Link
            1. Solution
          3. Statement Order Matters in Top-Level Code
            1. Solution
          4. Recursive “from” Imports May Not Work
            1. Solutions
          5. reload May Not Impact from Imports
            1. Solution
          6. reload Isn’t Applied Transitively
            1. Solution
        8. Summary
        9. Exercises
      6. 6. Classes
        1. Why Use Classes?
        2. Class Basics
          1. Classes Generate Multiple Instance Objects
            1. Class objects provide default behavior
            2. Instance objects are generated from classes
            3. An example
          2. Classes Are Specialized by I nheritance
            1. An example
          3. Classes Can Intercept Python Operators
            1. An example
        3. Using the Class Statement
          1. General Form
          2. Example
        4. Using Class Methods
          1. Example
        5. Inheritance Searches Namespace Trees
          1. Attribute Tree Construction
          2. Specializing Inherited Methods
        6. Operator Overloading in Classes
          1. Common Operator Overloading Methods
          2. Examples
            1. __getitem__ intercepts all index references
            2. __getattr__ catches undefined attribute references
            3. _ _repr__ returns a string representation
        7. Namespace Rules: The Whole Story
          1. Unqualified Names: Global Unless Assigned
          2. Qualified Names: Object Namespaces
          3. N amespace Dictionaries
        8. Designing with Classes
          1. Python and OOP
          2. OOP and Inheritance: “is-a”
          3. OOP and Composition: “has-a”
          4. OOP and Delegation
          5. Extending Built-in Object Types
          6. Multiple Inheritance
          7. Classes Are Objects: Generic Object Factories
          8. Methods Are Objects: Bound or Unbound
        9. Odds and Ends
          1. Private Attributes (New in 1.5)
          2. Documentation Strings
          3. C lasses Versus Modules
        10. Class Gotchas
          1. Changing Class Attributes Can Have Side Effects
            1. Solution
          2. Multiple Inheritance: Order Matters
            1. Solution
          3. Class Function Attributes Are Special
            1. Solution
          4. Methods, Classes, and Nested Scopes
            1. Solution
        11. Summary
        12. Exercises
      7. 7. Exceptions
        1. Why Use Exceptions?
        2. Exception Basics
          1. try/except/else
          2. try/finally
          3. raise
          4. First Examples
            1. Default behavior: Error messages
            2. Catching built-in exceptions
            3. Raising and catching user-defined exceptions
        3. Exception Idioms
          1. Exceptions Aren’t Always a Bad Thing
          2. Searches Sometimes Signal Success by raise
          3. Outer try Statements Can Debug Code
        4. Exception Catching Modes
          1. try Statement Clauses
          2. Catching 1-of-N Exceptions
          3. Exceptions Nest at Runtime
          4. finally Clauses Run “On the Way Out”
        5. Odds and Ends
          1. Passing Optional Data
          2. The assert Statement
          3. Class Exceptions
            1. General raise forms
            2. Example
        6. Exception Gotchas
          1. Exceptions Match by Identity, Not Equality
          2. Catching Too Much?
            1. Solution
          3. Catching Too Little?
            1. Solution
        7. Summary
        8. Exercises
    3. II. The Outer Layers
      1. 8. Built-in Tools
        1. Aside: The sys Module
        2. Built-in Functions
          1. Conversions, Numbers, and Comparisons
          2. Attribute Manipulation
          3. Executing Programs
        3. Library Modules
          1. Basic String Operations: The string Module
          2. Advanced String Operations: The re Module
            1. Regular expressions
            2. A real regular expression problem
          3. Generic Operating-System Interfaces: The os Module
            1. The os and os.path modules
          4. Copying Files and Directories: The shutil Module
          5. Internet-Related Modules
            1. The Common Gateway Interface: The cgi module
            2. Manipulating URLs: the urllib and urlparse modules
            3. Specific Internet protocols
            4. Processing Internet data
          6. Dealing with Binary Data: The struct Module
          7. Debugging, Timing, Profiling
        4. Exercises
      2. 9. Common Tasks in Python
        1. Data Structure Manipulations
          1. Making Copies Inline
          2. Making Copies: The copy Module
          3. Sorting and Randomizing
          4. Randomizing: The random Module
          5. Making New Data Structures
          6. Making New Lists and Dictionaries: The UserList and UserDict Modules
        2. Manipulating Files
          1. Doing Something to Each Line in a File
            1. Choosing chunk sizes
          2. Doing Something to a Set of Files Specified on the Command Line
          3. The f ileinput Module
          4. Filenames and Directories
          5. Matching Sets of Files: The glob Module
          6. Using Temporary Files
          7. More on Scanning Text Files
        3. Manipulating Programs
          1. Calling Other Programs
        4. Internet-Related Activities
          1. Downloading a Web Page Programmatically
          2. Checking the Validity of Links and Mirroring Web Sites: webchecker.py and Friends
          3. Checking Mail
        5. Bigger Examples
          1. Compounding Your Interest
          2. An Automated Dial-Out Script
          3. An Interactive Rolodex
        6. Exercises
      3. 10. Frameworks and Applications
        1. An Automated Complaint System
        2. Interfacing with COM: Cheap Public Relations
        3. A Tkinter-Based GUI Editor for Managing Form Data
        4. Design Considerations
        5. JPython: The Felicitous Union of Python and Java
          1. JPython Gives Python Programmers Access to Java Libraries
          2. JPython as a Java Scripting Language
          3. A Real JPython/Swing Application: grapher.py
        6. Other Frameworks and Applications
          1. Python Imaging Library (PIL)
          2. Numeric Python (NumPy)
          3. SWIG
          4. Python MegaWidgets (Pmw)
          5. ILU and Fnorb
        7. Exercises
    4. III. Appendixes
      1. A. Python Resources
        1. The Python Language Web Site
        2. Python Software
          1. The Standard Python Distribution
          2. Gifts from Guido
          3. Offerings from Commercial Vendors
            1. Scriptics Corporation’s Tcl/Tk toolkits
            2. Digital Creation’s free releases
            3. Pythonware
          4. Other Modules and Packages
          5. Emacs Support
        3. Python Documentation and Books
          1. The Standard Python Documentation Set
          2. The FAQ
          3. Other Published Books
          4. Other Sources of Documentation
        4. Newsgroups, Discussion Groups, and Email Help
          1. comp.lang.python/python-list
          2. comp.lang.python.announce/python-list-announce
          3. python-help@python.org
          4. The SIGs
          5. JPython-interest
        5. Conferences
        6. Support Companies, Consultants, Training
        7. Tim Peters
      2. B. Platform-Specific Topics
        1. Unix
          1. Unix-Specific Extensions
            1. Standard distribution
            2. SGI-specific extensions
            3. SunOS-specific extensions
            4. Other Unix resources
        2. Windows-Specific Information
        3. Macintosh-Specific Information
        4. Java
        5. Other Platforms
      3. C. Solutions to Exercises
        1. Chapter 1
        2. Chapter 2
        3. Chapter 3
        4. Chapter 4
        5. Chapter 5
        6. Chapter 6
        7. Chapter 7
        8. Chapter 8
        9. Chapter 9
        10. Chapter 10
    5. Index
    6. Colophon

Product information

  • Title: Learning Python
  • Author(s):
  • Release date: April 1999
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781565924642