Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Buy Now $31.99
Standard view
Full view
of .
Save to My Library
Look up keyword or section
Like this
20Activity

Table Of Contents

Preface1
PART I
I.Getting Started
Chapter 1
CHAPTER 1
A Python Q&A Session1
Why Do People Use Python?
Developer productivity
Program portability
Support libraries
Component integration
Software Quality
Developer Productivity
Is Python a “Scripting Language”?
Shell tools
Control language
OK, but What’s the Downside?
Who Uses Python Today?
What Can I Do with Python?
Systems Programming
Internet Scripting
Component Integration
Database Programming
Rapid Prototyping
Gaming, Images, AI, XML, Robots, and More
What Are Python’s Technical Strengths?
It’s Object Oriented
Automatic memory management
Programming-in-the-large support
Built-in object types
Library utilities
Third-party utilities
It’s Easy to Use
It’s Easy to Learn
It’s Named After Monty Python
How Does Python Stack Up to Language X?
Chapter Summary
BRAIN BUILDER
Chapter Quiz
Quiz Answers
Chapter 2
CHAPTER 2
How Python Runs Programs 2
Introducing the Python Interpreter
Program Execution
The Programmer’s View
Python’s View
Byte code compilation
The Python Virtual Machine (PVM)
Performance implications
Development implications
Execution Model Variations
Python Implementation Alternatives
CPython
Jython
IronPython
Execution Optimization Tools
The Psyco just-in-time compiler
The Shedskin C++ translator
Frozen Binaries
Chapter 3
CHAPTER 3
How You Run Programs 3
Interactive Coding
Using the Interactive Prompt
System Command Lines and Files
Using Command Lines and Files
Unix Executable Scripts (#!)
Clicking File Icons
Clicking Icons on Windows
The raw_input Trick
Other Icon-Click Limitations
Module Imports and Reloads
The Grander Module Story: Attributes
Modules and namespaces
import and reload Usage Notes
The IDLE User Interface
IDLE Basics
Using IDLE
Advanced IDLE Tools
Other IDEs
Embedding Calls
Frozen Binary Executables
Text Editor Launch Options
Other Launch Options
Future Possibilities?
Which Option Should I Use?
PART II
II.Types and Operations
Chapter 4
CHAPTER 4
Introducing Python Object Types4
Why Use Built-in Types?
Python’s Core Data Types
Numbers
Strings
Sequence Operations
Immutability
Getting Help
Other Ways to Code Strings
Pattern Matching
Lists
Type-Specific Operations
Bounds Checking
Nesting
List Comprehensions
Dictionaries
Mapping Operations
Nesting Revisited
Booleans
Third-Party Extensions
Chapter 6
CHAPTER 6
The Dynamic Typing Interlude 6
The Case of the Missing Declaration Statements
Variables, Objects, and References
Types Live with Objects, Not Variables
Objects Are Garbage-Collected
Shared References
Shared References and In-Place Changes
Shared References and Equality
Dynamic Typing Is Everywhere
Chapter 7
CHAPTER 7
Strings7
String Literals
Index, slice, length
Iteration, membership
Single- and Double-Quoted Strings Are the Same
Escape Sequences Represent Special Bytes
Raw Strings Suppress Escapes
Triple Quotes Code Multiline Block Strings
Unicode Strings Encode Larger Character Sets
Strings in Action
Basic Operations
Indexing and Slicing
Extended slicing: the third limit
String Conversion Tools
Character code conversions
Changing Strings
String Formatting
Advanced String Formatting
Dictionary-Based String Formatting
String Methods
String Method Examples: Changing Strings
String Method Examples: Parsing Text
Other Common String Methods in Action
The Original string Module
General Type Categories
Types Share Operation Sets by Categories
Mutable Types Can Be Changed In-Place
Chapter 8
CHAPTER 8
Lists and Dictionaries 8
Ordered collections of arbitrary objects
Of the category mutable sequence
Arrays of object references
Lists in Action
Basic List Operations
Indexing, Slicing, and Matrixes
Changing Lists In-Place
Index and slice assignments
List method calls
Other common list operations
Unordered collections of arbitrary objects
Of the category mutable mapping
Dictionaries in Action
Basic Dictionary Operations
Changing Dictionaries In-Place
More Dictionary Methods
A Languages Table
Dictionary Usage Notes
Using dictionaries to simulate flexible lists
Using dictionaries for sparse data structures
Avoiding missing-key errors
Using dictionaries as “records”
Other ways to make dictionaries
Chapter 9
CHAPTER 9
Tuples, Files, and Everything Else 9
Of the category immutable sequence
Tuples in Action
Tuple syntax peculiarities: commas and parentheses
Conversions and immutability
Why Lists and Tuples?
Opening Files
Using Files
Files in Action
Storing and parsing Python objects in files
Storing native Python objects with pickle
Storing and parsing packed binary data in files
Other File Tools
Type Categories Revisited
Object Flexibility
References Versus Copies
Comparisons, Equality, and Truth
The Meaning of True and False in Python
Python’s Type Hierarchies
Other Types in Python
Built-in Type Gotchas
Assignment Creates References, Not Copies
Repetition Adds One Level Deep
Beware of Cyclic Data Structures
Immutable Types Can’t Be Changed In-Place
PART III
III.Statements and Syntax
Chapter 10
CHAPTER 10
Introducing Python Statements10
Python Program Structure Revisited
Python’s Statements
A Tale of Two ifs
What Python Adds
What Python Removes
Parentheses are optional
End of line is end of statement
End of indentation is end of block
Why Indentation Syntax?
A Few Special Cases
Statement rule special cases
Block rule special case
A Quick Example: Interactive Loops
A Simple Interactive Loop
Doing Math on User Inputs
Handling Errors by Testing Inputs
Handling Errors with try Statements
Nesting Code Three Levels Deep
Chapter 11
CHAPTER 11
Assignment, Expressions, and print11
Assignment Statements
Assignment Statement Forms
Tuple- and list-unpacking assignments
Multiple-target assignments
Sequence Assignments
Advanced sequence assignment patterns
Multiple-Target Assignments
Multiple-target assignment and shared references
Augmented Assignments
Augmented assignment and shared references
Variable Name Rules
Naming conventions
Names have no type, but objects do
Expression Statements
Expression Statements and In-Place Changes
print Statements
The Python “Hello World” Program
Redirecting the Output Stream
The print >> file Extension
Chapter 12
CHAPTER 12
if Statements
General Format
Basic Examples
Multiway Branching
Python Syntax Rules
Block Delimiters
Statement Delimiters
Truth Tests
The if/else Ternary Expression
Why You Will Care: Booleans
Chapter 13
CHAPTER 13
while and for Loops 13
while Loops
Examples
break, continue, pass, and the Loop else
General Loop Format
pass
continue
break
else
More on the loop else clause
for Loops
Basic usage
Other data types
PyDoc: HTML Reports
Standard Manual Set
Web Resources
Published Books
Common Coding Gotchas
PART IV
IV.Functions
Chapter 15
CHAPTER 15
Function Basics15
Why Use Functions?
Maximizing code reuse and minimizing redundancy
Procedural decomposition
Coding Functions
def Statements
def Executes at Runtime
A First Example: Definitions and Calls
Calls
Polymorphism in Python
A Second Example: Intersecting Sequences
Polymorphism Revisited
Local Variables
Chapter 16
CHAPTER 16
Scopes and Arguments 16
Scope Rules
Python Scope Basics
Name Resolution: The LEGB Rule
Scope Example
The Built-in Scope
The global Statement
Minimize Global Variables
Minimize Cross-File Changes
Other Ways to Access Globals
Scopes and Nested Functions
Nested Scope Details
Nested Scope Examples
Factory functions
Retaining enclosing scopes’ state with defaults
Nested scopes and lambdas
Scopes versus defaults with loop variables
Arbitrary scope nesting
Passing Arguments
Arguments and Shared References
Avoiding Mutable Argument Changes
Simulating Output Parameters
Special Argument-Matching Modes
Keyword and Default Examples
Keywords
Defaults
Arbitrary Arguments Examples
Collecting arguments
Unpacking arguments
Combining Keywords and Defaults
The min Wakeup Call
Full credit
Bonus points
The punch line
A More Useful Example: General Set Functions
Argument Matching: The Gritty Details
Chapter 17
CHAPTER 17
Advanced Function Topics 17
Anonymous Functions: lambda
lambda Expressions
Why Use lambda?
How (Not) to Obfuscate Your Python Code
Nested lambdas and Scopes
Why You Will Care: Callbacks
Applying Functions to Arguments
The apply Built-in
Passing keyword arguments
apply-Like Call Syntax
Mapping Functions over Sequences: map
Functional Programming Tools: filter and reduce
List Comprehensions Revisited: Mappings
Adding Tests and Nested Loops
List Comprehensions and Matrixes
Comprehending List Comprehensions
Iterators Revisited: Generators
Generator Function Example
Extended Generator Function Protocol: send Versus next
Iterators and Built-in Types
Generator Expressions: Iterators Meet List Comprehensions
Timing Iteration Alternatives
Function Design Concepts
Functions Are Objects: Indirect Calls
Function Gotchas
Local Names Are Detected Statically
Defaults and Mutable Objects
Functions Without returns
Enclosing Scope Loop Variables
PART V
V.Modules
Chapter 18
CHAPTER 18
Modules: The Big Picture18
Why Use Modules?
System namespace partitioning
Implementing shared services or data
Python Program Architecture
How to Structure a Program
Imports and Attributes
Standard Library Modules
How Imports Work
1. Find It
The module search path
PYTHONPATH directories
Standard library directories
.pth file directories
The sys.path list
Advanced module selection concepts
2. Compile It (Maybe)
3. Run It
Chapter 19
CHAPTER 19
Module Coding Basics 19
Module Creation
Module Usage
The import Statement
The from statement
The from * Statement
Imports Happen Only Once
import and from Are Assignments
Cross-File Name Changes
import and from Equivalence
Potential Pitfalls of the from Statement
When import is required
Module Namespaces
Files Generate Namespaces
Attribute Name Qualification
Imports Versus Scopes
Namespace Nesting
Reloading Modules
reload Basics
reload Example
Chapter 20
CHAPTER 20
Module Packages20
Package Import Basics
Packages and Search Path Settings
Package __init__.py Files
Package initialization
Module namespace initialization
Package Import Example
from Versus import with Packages
Why Use Package Imports?
A Tale of Three Systems
Chapter 21
CHAPTER 21
Advanced Module Topics 21
Data Hiding in Modules
Minimizing from * Damage: _X and __all__
Enabling Future Language Features
Mixed Usage Modes: __name__ and __main__
Coding Class Trees
OOP Is About Code Reuse
Chapter 23
CHAPTER 23
Class Coding Basics23
Classes Generate Multiple Instance Objects
Class Objects Provide Default Behavior
Instance Objects Are Concrete Items
A First Example
Classes Are Customized by Inheritance
A Second Example
Classes Are Attributes in Modules
Classes Can Intercept Python Operators
A Third Example
Why Use Operator Overloading?
The World’s Simplest Python Class
Namespace Dictionaries
Namespace Links
A More Realistic Example
Chapter 25
CHAPTER 25
Designing with Classes 25
Python and OOP
Overloading by Call Signatures (or Not)
Classes As Records
OOP and Inheritance: “Is-a” Relationships
OOP and Composition: “Has-a” Relationships
Stream Processors Revisited
OOP and Delegation
Why You Will Care: Classes and Persistence
Multiple Inheritance
Classes Are Objects: Generic Object Factories
Why Factories?
Methods Are Objects: Bound or Unbound
Documentation Strings Revisited
Why You Will Care: Bound Methods and Callbacks
Classes Versus Modules
Chapter 26
CHAPTER 26
Advanced Class Topics26
Extending Built-in Types
Extending Types by Embedding
Extending Types by Subclassing
Pseudoprivate Class Attributes
Name Mangling Overview
Why Use Pseudoprivate Attributes?
New-Style Classes
Diamond Inheritance Change
Diamond inheritance example
Other New-Style Class Extensions
Static and class methods
Instance slots
Class properties
New __getattribute__ overloading method
Static and Class Methods
Using Static and Class Methods
Function Decorators
Decorator Example
Class Gotchas
Changing Class Attributes Can Have Side Effects
Multiple Inheritance: Order Matters
Methods, Classes, and Nested Scopes
“Overwrapping-itis”
PART VII
VII.Exceptions and Tools
Chapter 27
CHAPTER 27
Exception Basics27
Why Use Exceptions?
Exception Roles
Special-case handling
Unusual control flows
Exception Handling: The Short Story
The try/except/else Statement
try Statement Clauses
The try/else Clause
Example: Default Behavior
Example: Catching Built-in Exceptions
The try/finally Statement
Example: Coding Termination Actions with try/finally
Combining finally and except by Nesting
The raise Statement
Example: Raising and Catching User-Defined Exceptions
Example: Passing Extra Data with raise
Example: Propagating Exceptions with raise
The assert Statement
Example: Trapping Constraints (but Not Errors)
with/as Context Managers
Basic Usage
The Context Management Protocol
Chapter 28
CHAPTER 28
Exception Objects 28
String-Based Exceptions
String Exceptions Are Right Out!
Class-Based Exceptions
Class Exception Example
Why Class Exceptions?
Built-in Exception Classes
Specifying Exception Text
Sending Extra Data and Behavior in Instances
Example: Extra data with classes and strings
General raise Statement Forms
Chapter 29
CHAPTER 29
Designing with Exceptions29
Nesting Exception Handlers
Example: Control-Flow Nesting
Example: Syntactic Nesting
Exception Idioms
Exceptions Aren’t Always Errors
Functions Signal Conditions with raise
Debugging with Outer try Statements
Running In-Process Tests
More on sys.exc_info
Exception Design Tips
What Should Be Wrapped
Catching Too Much: Avoid Empty excepts
Catching Too Little: Use Class-Based Categories
String Exceptions Match by Identity, Not by Value
Core Language Summary
Development Tools for Larger Projects
PART VIII
APPENDIX A
Installation and Configuration1
Where to Fetch Python
The Python 2.5 MSI Installer on Windows Vista
Appendix B
APPENDIX B
Solutions to End-of-Part Exercises 2
Part III, Statements and Syntax
Part VI, Classes and OOP
Part VII, Exceptions and Tools
Index
P. 1
Learning Python

Learning Python

Ratings:

3.84

(137)
|Views: 34,926|Likes:
Portable, powerful, and a breeze to use, Python is ideal for both standalone programs and scripting applications. With this hands-on book, you can master the fundamentals of the core Python language quickly and efficiently, whether you're new to programming or just new to Python. Once you finish, you will know enough about the language to use it in any application domain you choose.Learning Python is based on material from author Mark Lutz's popular training courses, which he's taught over the past decade. Each chapter is a self-contained lesson that helps you thoroughly understand a key component of Python before you continue. Along with plenty of annotated examples, illustrations, and chapter summaries, every chapter also contains Brain Builder, a unique section with practical exercises and review quizzes that let you practice new skills and test your understanding as you go.This book covers:Types and Operations -- Python's major built-in object types in depth: numbers, lists, dictionaries, and moreStatements and Syntax -- the code you type to create and process objects in Python, along with Python's general syntax modelFunctions -- Python's basic procedural tool for structuring and reusing codeModules -- packages of statements, functions, and other tools organized into larger componentsClasses and OOP -- Python's optional object-oriented programming tool for structuring code for customization and reuseExceptions and Tools -- exception handling model and statements, plus a look at development tools for writing larger programsLearning Python gives you a deep and complete understanding of the language that will help you comprehend any application-level examples of Python that you later encounter. If you're ready to discover what Google and YouTube see in Python, this book is the best way to get started.
Portable, powerful, and a breeze to use, Python is ideal for both standalone programs and scripting applications. With this hands-on book, you can master the fundamentals of the core Python language quickly and efficiently, whether you're new to programming or just new to Python. Once you finish, you will know enough about the language to use it in any application domain you choose.Learning Python is based on material from author Mark Lutz's popular training courses, which he's taught over the past decade. Each chapter is a self-contained lesson that helps you thoroughly understand a key component of Python before you continue. Along with plenty of annotated examples, illustrations, and chapter summaries, every chapter also contains Brain Builder, a unique section with practical exercises and review quizzes that let you practice new skills and test your understanding as you go.This book covers:Types and Operations -- Python's major built-in object types in depth: numbers, lists, dictionaries, and moreStatements and Syntax -- the code you type to create and process objects in Python, along with Python's general syntax modelFunctions -- Python's basic procedural tool for structuring and reusing codeModules -- packages of statements, functions, and other tools organized into larger componentsClasses and OOP -- Python's optional object-oriented programming tool for structuring code for customization and reuseExceptions and Tools -- exception handling model and statements, plus a look at development tools for writing larger programsLearning Python gives you a deep and complete understanding of the language that will help you comprehend any application-level examples of Python that you later encounter. If you're ready to discover what Google and YouTube see in Python, this book is the best way to get started.

More info:

Publish date: Nov 21, 2007
Added to Scribd: May 16, 2009
Copyright:Traditional Copyright: All rights reservedISBN:9780596516604
List Price: $31.99 Buy Now

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
See more
See less

03/27/2014

748

9780596516604

$31.99

USD

pdf

original

You're Reading a Free Preview
Pages 30 to 126 are not shown in this preview.
You're Reading a Free Preview
Pages 156 to 302 are not shown in this preview.
You're Reading a Free Preview
Pages 332 to 474 are not shown in this preview.
You're Reading a Free Preview
Pages 504 to 525 are not shown in this preview.
You're Reading a Free Preview
Pages 555 to 748 are not shown in this preview.

Activity (20)

You've already reviewed this. Edit your review.
mcandre_1 reviewed this
Rated 5/5
Very helpful for beginning and intermediate Python programmers. This book is The C Programming Language, for Pythonistas.
cald_4 reviewed this
Rated 5/5
Great introduction to Python. I went through quickly through it without a computer to grasp the syntax, and was later able to start writing my first programs.Although some might argue that there you can find the same content on the Internet, it's much easier for me to read from a book.
1 hundred reads
1 thousand reads
Ben Morris liked this
Dan Childs liked this
Chunhua WU liked this
Tato Kutalia liked this

You're Reading a Free Preview

Download
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->