Text stringlengths 1 9.41k |
|---|
If I could become more
clairvoyant, I would, but the Web changes faster than printed books.
###### About the Programs in This Book
This fourth edition of this book, and all the program examples in it, is based on Python
version 3.0. |
In addition, most of its examples run under Python 2.6, as described in the
text, and notes for Python 2.6 readers are mixed in along the way.
Because this text focuses on the core language, however, you can be fairly sure that
most of what it has to say won’t change very much in future releases of Python. |
Most
of this book applies to earlier Python versions, too, except when it does not; naturally,
if you try using extensions added after the release you’ve got, all bets are off.
As a rule of thumb, the latest Python is the best Python. |
Because this book focuses on
the core language, most of it also applies to Jython, the Java-based Python language
implementation, as well as other Python implementations described in Chapter 2.
Source code for the book’s examples, as well as exercise solutions, can be fetched from
the book’s website at http://www.orei... |
So, how do you
run the examples? |
We’ll study startup details in Chapter 3, so please stay tuned for
information on this front.
###### Using Code Examples
This book is here to help you get your job done. |
In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. |
For example,
**f** **|**
-----
writing a program that uses several chunks of code from this book does not require
permission. |
Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
code does not require permission. |
Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. |
An attribution usually includes the title,
author, publisher, and ISBN. For example: “Learning Python, Fourth Edition, by Mark
Lutz. |
Copyright 2009 Mark Lutz, 978-0-596-15806-4.”
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at permissions@oreilly.com.
###### Font Conventions
This book uses the following typographical conventions:
_Italic_
Used for email addresses, URLs, filen... |
Don’t type the % character (or the system prompt it sometimes
stands for) yourself.
Similarly, in interpreter interaction listings, do not type the `>>>`
and ... |
characters shown at the start of lines—these are prompts that
Python displays. Type just the text after these prompts. |
To help you
remember this, user inputs are shown in bold font in this book.
Also, you normally don’t need to type text that starts with a # in listings;
as you’ll learn, these are comments, not executable code.
###### Safari® Books Online
Safari Books Online is an on-demand digital library that lets you easily
searc... |
Access new titles before they are
available for print, and get exclusive access to manuscripts in development and post
feedback for the authors. |
Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from
tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. |
To have full
digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com.
###### How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Seba... |
You can access this page at:
_http://www.oreilly.com/catalog/9780596158064/_
**f** **|**
-----
To comment or ask technical questions about this book, send email to:
_bookquestions@oreilly.com_
For more information about our books, conferences, Resource Centers, and the
O’Reilly Network, see our website at:
_htt... |
I have now been using and promoting Python for 17 years,
and have been teaching it for 12 years. |
Despite the passage of time and events, I am still
constantly amazed at how successful Python has been over the years. It has grown in
ways that most of us could not possibly have imagined in 1992. |
So, at the risk of
sounding like a hopelessly self-absorbed author, you’ll have to pardon a few words of
reminiscing, congratulations, and thanks here.
It’s been the proverbial long and winding road. |
Looking back today, when I first discovered Python in 1992, I had no idea what an impact it would have on the next 17
years of my life. |
Two years after writing the first edition of Programming Python in
1995, I began traveling around the country and the world teaching Python to beginners
and experts. |
Since finishing the first edition of Learning Python in 1999, I’ve been an
independent Python trainer and writer, thanks largely to Python’s exponential growth
in popularity.
As I write these words in mid-2009, I have written 12 Python books (4 editions of 3).
I have also been teaching Python for more than a decade; h... |
Besides racking up frequent flyer miles, these classes helped
me refine this text as well as my other Python books. Over the years, teaching honed
the books, and vice versa. |
In fact, the book you’re reading is derived almost entirely
from my classes.
Because of this, I’d like to thank all the students who have participated in my courses
during the last 12 years. |
Along with changes in Python itself, your feedback played a
huge role in shaping this text. |
(There’s nothing quite as instructive as watching 3,000
students repeat the same beginner’s mistakes!) This edition owes its changes primarily
to classes held after 2003, though every class held since 1997 has in some way helped
refine this book. |
I’d especially like to single out clients who hosted classes in Dublin,
Mexico City, Barcelona, London, Edmonton, and Puerto Rico; better perks would be
hard to imagine.
I’d also like to express my gratitude to everyone who played a part in producing this
book. |
To the editors who worked on this project: Julie Steele on this edition, Tatiana
**|** **f**
-----
Apandi on the prior edition, and many others on earlier editions. |
To Doug Hellmann
and Jesse Noller for taking part in the technical review of this book. |
And to O’Reilly
for giving me a chance to work on those 12 book projects—it’s been net fun (and only
feels a little like the movie Groundhog Day).
I want to thank my original coauthor David Ascher as well for his work on the first two
editions of this book. |
David contributed the “Outer Layers” part in prior editions,
which we unfortunately had to trim to make room for new core language materials in
the third edition. |
To compensate, I added a handful of more advanced programs as a
self-study final exercise in the third edition, and added both new advanced examples
and a new complete part for advanced topics in the fourth edition. |
Also see the prior
notes in this Preface about follow-up application-level texts you may want to consult
once you’ve learned the fundamentals here.
For creating such an enjoyable and useful language, I owe additional thanks to Guido
van Rossum and the rest of the Python community. |
Like most open source systems,
Python is the product of many heroic efforts. After 17 years of programming Python, I
still find it to be seriously fun. |
It’s been my privilege to watch Python grow from a new
kid on the scripting languages block to a widely used tool, deployed in some fashion
by almost every organization writing software. |
That has been an exciting endeavor to
be a part of, and I’d like to thank and congratulate the entire Python community for a
job well done.
I also want to thank my original editor at O’Reilly, the late Frank Willison. |
This book
was largely Frank’s idea, and it reflects the contagious vision he had. In looking back,
Frank had a profound impact on both my own career and that of Python itself. |
It is not
an exaggeration to say that Frank was responsible for much of the fun and success of
Python when it was new. We still miss him.
Finally, a few personal notes of thanks. |
To OQO for the best toys so far (while they
lasted). To the late Carl Sagan for inspiring an 18-year-old kid from Wisconsin. To my
Mom, for courage. |
And to all the large corporations I’ve come across over the years,
for reminding me how lucky I have been to be self-employed for the last decade!
To my children, Mike, Sammy, and Roxy, for whatever futures you will choose to make.
You were children when I began with Python, and you seem to have somehow grown
up along... |
Life may compel us down paths all our own, but
there will always be a path home.
And most of all, to Vera, my best friend, my girlfriend, and my wife. |
The best day of
my life was the day I finally found you. |
I don’t know what the next 50 years hold, but
I do know that I want to spend all of them holding you.
—Mark Lutz
Sarasota, Florida
July 2009
**f** **|**
-----
-----
##### PART I
## Getting Started
-----
-----
###### CHAPTER 1
### A Python Q&A Session
If you’ve bought this book, you may already know what Pyth... |
If you don’t, you probably won’t be sold on Python until you’ve
learned the language by reading the rest of this book and have done a project or two.
But before we jump into details, the first few pages of this book will briefly introduce
some of the main reasons behind Python’s popularity. |
To begin sculpting a definition
of Python, this chapter takes the form of a question-and-answer session, which poses
some of the most common questions asked by beginners.
###### Why Do People Use Python?
Because there are many programming languages available today, this is the usual first
question of newcomers. |
Given that there are roughly 1 million Python users out there
at the moment, there really is no way to answer this question with complete accuracy;
the choice of development tools is sometimes based on unique constraints or personal
preference.
But after teaching Python to roughly 225 groups and over 3,000 students du... |
The primary factors cited by Python
users seem to be these:
_Software quality_
For many, Python’s focus on readability, coherence, and software quality in general
sets it apart from other tools in the scripting world. |
Python code is designed to be
readable, and hence reusable and maintainable—much more so than traditional
scripting languages. |
The uniformity of Python code makes it easy to understand,
even if you did not write it. |
In addition, Python has deep support for more advanced
software reuse mechanisms, such as object-oriented programming (OOP).
_Developer productivity_
Python boosts developer productivity many times beyond compiled or statically
typed languages such as C, C++, and Java. |
Python code is typically one-third to
one-fifth the size of equivalent C++ or Java code. That means there is less to type,
-----
less to debug, and less to maintain after the fact. |
Python programs also run immediately, without the lengthy compile and link steps required by some other tools,
further boosting programmer speed.
_Program portability_
Most Python programs run unchanged on all major computer platforms. |
Porting
Python code between Linux and Windows, for example, is usually just a matter of
copying a script’s code between machines. |
Moreover, Python offers multiple options for coding portable graphical user interfaces, database access programs, webbased systems, and more. |
Even operating system interfaces, including program
launches and directory processing, are as portable in Python as they can possibly
be.
_Support libraries_
Python comes with a large collection of prebuilt and portable functionality, known
as the _standard library. |
This library supports an array of application-level pro-_
gramming tasks, from text pattern matching to network scripting. |
In addition,
Python can be extended with both homegrown libraries and a vast collection of
third-party application support software. |
Python’s third-party domain offers tools
for website construction, numeric programming, serial port access, game development, and much more. |
The NumPy extension, for instance, has been described
as a free and more powerful equivalent to the Matlab numeric programming
system.
_Component integration_
Python scripts can easily communicate with other parts of an application, using a
variety of integration mechanisms. |
Such integrations allow Python to be used as a
product customization and extension tool. |
Today, Python code can invoke C and
C++ libraries, can be called from C and C++ programs, can integrate with Java
and .NET components, can communicate over frameworks such as COM, can
interface with devices over serial ports, and can interact over networks with interfaces like SOAP, XML-RPC, and CORBA. |
It is not a standalone tool.
_Enjoyment_
Because of Python’s ease of use and built-in toolset, it can make the act of programming more pleasure than chore. |
Although this may be an intangible benefit,
its effect on productivity is an important asset.
Of these factors, the first two (quality and productivity) are probably the most compelling benefits to most Python users.
###### Software Quality
By design, Python implements a deliberately simple and readable syntax and a... |
As a slogan at a recent Python conference attests, the
net result is that Python seems to “fit your brain”—that is, features of the language
interact in consistent and limited ways and follow naturally from a small set of core
**|**
-----
concepts. |
This makes the language easier to learn, understand, and remember. |
In practice, Python programmers do not need to constantly refer to manuals when reading or
writing code; it’s a consistently designed system that many find yields surprisingly
regular-looking code.
By philosophy, Python adopts a somewhat minimalist approach. |
This means that although there are usually multiple ways to accomplish a coding task, there is usually
just one obvious way, a few less obvious alternatives, and a small set of coherent interactions everywhere in the language. |
Moreover, Python doesn’t make arbitrary decisions for you; when interactions are ambiguous, explicit intervention is preferred over
“magic.” In the Python way of thinking, explicit is better than implicit, and simple is
better than complex.[*]
Beyond such design themes, Python includes tools such as modules and OOP th... |
And because Python is focused on quality, so too,
naturally, are Python programmers.
###### Developer Productivity
During the great Internet boom of the mid-to-late 1990s, it was difficult to find enough
programmers to implement software projects; developers were asked to implement
systems as fast as the Internet evo... |
Today, in an era of layoffs and economic recession, the picture has shifted. |
Programming staffs are often now asked to accomplish
the same tasks with even fewer people.
In both of these scenarios, Python has shined as a tool that allows programmers to get
more done with less effort. |
It is deliberately optimized for speed of development—its
simple syntax, dynamic typing, lack of compile steps, and built-in toolset allow programmers to develop programs in a fraction of the time needed when using some other
tools. |
The net effect is that Python typically boosts developer productivity many times
beyond the levels supported by traditional languages. |
That’s good news in both boom
and bust times, and everywhere the software industry goes in between.
###### Is Python a “Scripting Language”?
Python is a general-purpose programming language that is often applied in scripting
roles. |
It is commonly defined as an object-oriented scripting language—a definition that
blends support for OOP with an overall orientation toward scripting roles. |
In fact,
people often use the word “script” instead of “program” to describe a Python code file.
In this book, the terms “script” and “program” are used interchangeably, with a slight
- For a more complete look at the Python philosophy, type the command import this at any Python interactive
prompt (you’ll see how in C... |
This invokes an “Easter egg” hidden in Python—a collection of design
principles underlying Python. |
The acronym EIBTI is now fashionable jargon for the “explicit is better than
implicit” rule.
**|**
-----
preference for “script” to describe a simpler top-level file and “program” to refer to a
more sophisticated multifile application.
Because the term “scripting language” has so many different meanings to differe... |
In fact, people tend
to make three very different associations, some of which are more useful than others,
when they hear Python labeled as such:
_Shell tools_
Sometimes when people hear Python described as a scripting language, they think
it means that Python is a tool for coding operating-system-oriented scripts. |
Such
programs are often launched from console command lines and perform tasks such
as processing text files and launching other programs.
Python programs can and do serve such roles, but this is just one of dozens of
common Python application domains. |
It is not just a better shell-script language.
_Control language_
To others, scripting refers to a “glue” layer used to control and direct (i.e., script)
other application components. |
Python programs are indeed often deployed in the
context of larger applications. |
For instance, to test hardware devices, Python programs may call out to components that give low-level access to a device. |
Similarly,
programs may run bits of Python code at strategic points to support end-user
product customization without the need to ship and recompile the entire system’s
source code.
Python’s simplicity makes it a naturally flexible control tool. |
Technically, though,
this is also just a common Python role; many (perhaps most) Python programmers
code standalone scripts without ever using or knowing about any integrated components. |
It is not just a control language.
_Ease of use_
Probably the best way to think of the term “scripting language” is that it refers to
a simple language used for quickly coding tasks. |
This is especially true when the
term is applied to Python, which allows much faster program development than
compiled languages like C++. |
Its rapid development cycle fosters an exploratory,
incremental mode of programming that has to be experienced to be appreciated.
Don’t be fooled, though—Python is not just for simple tasks. |
Rather, it makes tasks
simple by its ease of use and flexibility. Python has a simple feature set, but it allows
programs to scale up in sophistication as needed. |
Because of that, it is commonly
used for quick tactical tasks and longer-term strategic development.
So, is Python a scripting language or not? It depends on whom you ask. |
In general, the
term “scripting” is probably best used to describe the rapid and flexible mode of development that Python supports, rather than a particular application domain.
**|**
-----
###### OK, but What’s the Downside?
After using it for 17 years and teaching it for 12, the only downside to Python I’ve found... |
In short, the
standard implementations of Python today compile (i.e., translate) source code statements to an intermediate format known as byte code and then interpret the byte code.
Byte code provides portability, as it is a platform-independent format. |
However, because Python is not compiled all the way down to binary machine code (e.g., instructions for an Intel chip), some programs will run more slowly in Python than in a fully
compiled language like C.
Whether you will ever care about the execution speed difference depends on what kinds
of programs you write. |
Python has been optimized numerous times, and Python code
runs fast enough by itself in most application domains. |
Furthermore, whenever you do
something “real” in a Python script, like processing a file or constructing a graphical
user interface (GUI), your program will actually run at C speed, since such tasks are
immediately dispatched to compiled C code inside the Python interpreter. |
More fundamentally, Python’s speed-of-development gain is often far more important than any
speed-of-execution loss, especially given modern computer speeds.
Even at today’s CPU speeds, though, there still are some domains that do require optimal execution speeds. |
Numeric programming and animation, for example, often need
at least their core number-crunching components to run at C speed (or better). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.