-->
Navigation
The Quick Python Book, Second Edition

The Quick Python Book, Second Edition

Now pay Easier and Secure using Paypal
Price:

Read more

VERNON L. CEDER

FIRST EDITION BY DARYL K. HARMS & KENNETH M. McDONALD


e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 2.00
 Pages
 362 p
 File Size 
 2,910 KB
 File Type
 PDF format
 ISBN
 9781935182207
 Copyright©   
 2010 by Manning Publications Co 

About the Author
Second edition author Vern Ceder has been programming in various languages for
over 20 years and has been a Linux system administrator since 2000. He started using
Python for a variety of projects in 2001 and is director of technology at the Canterbury
School in Fort Wayne, Indiana, where he teaches Python to high school students and
teachers and gives talks to whomever will listen on Python and the benefits of teaching
programming in schools. An advocate for open software and open content, Vern is a
principal organizer of the Fort Wayne Linux Users Group.

About the cover illustration
The illustration on the cover of The Quick Python Book, Second Edition is taken from a
late 18th century edition of Sylvain Maréchal’s four-volume compendium of regional
dress customs published in France. Each illustration is finely drawn and colored by
hand. The rich variety of Maréchal’s collection reminds us vividly of how culturally
apart the world’s towns and regions were just 200 years ago. Isolated from each other,
people spoke different dialects and languages. In the streets or in the countryside, it
was easy to identify where they lived and what their trade or station in life was just by
what they were wearing.

Dress codes have changed since then and the diversity by region, so rich at the
time, has faded away. It is now hard to tell apart the inhabitants of different continents,
let alone different towns or regions. Perhaps we have traded cultural diversity
for a more varied personal life—certainly for a more varied and fast-paced technological life.

At a time when it is hard to tell one computer book from another, Manning celebrates
the inventiveness and initiative of the computer business with book covers
based on the rich diversity of regional life of two centuries ago, brought back to life by Maréchal’s pictures.

about this book
Who should read this book
This book is intended for people who already have experience in one or more programming
languages and want to learn the basics of Python 3 as quickly and directly
as possible. Although some basic concepts are covered, there’s no attempt to teach
basic programming skills in this book, and the basic concepts of flow control, OOP,
file access, exception handling, and the like are assumed. This book may also be of
use to users of earlier versions of Python who want a concise reference for Python 3.

How to use this book
Part 1 introduces Python and explains how to download and install it on your system.
It also includes a very general survey of the language, which will be most useful for
experienced programmers looking for a high-level view of Python.
Part 2 is the heart of the book. It covers the ingredients necessary for obtaining a
working knowledge of Python as a general-purpose programming language. The
chapters are designed to allow readers who are beginning to learn Python to work
their way through sequentially, picking up knowledge of the key points of the language.
These chapters also contain some more advanced sections, allowing you to
return to find in one place all the necessary information about a construct or topic.
Part 3 introduces advanced language features of Python, elements of the language
that aren’t essential to its use but that can certainly be a great help to a serious Python programmer.
Part 4 describes more advanced or specialized topics that are beyond the strict syntax
of the language. You may read these chapters or not, depending on your needs.
A suggested plan if you’re new to Python is to start by reading chapter 3 to obtain
an overall perspective and then work through the chapters in part 2 that are applicable.
Enter in the interactive examples as they are introduced. This will immediately
reinforce the concepts. You can also easily go beyond the examples in the text to
answer questions about anything that may be unclear. This has the potential to
amplify the speed of your learning and the level of your comprehension. If you aren’t
familiar with OOP or don’t need it for your application, skip most of chapter 15. If you
aren’t interested in developing a GUI, skip chapter 16.
Those familiar with Python should also start with chapter 3. It will be a good review
and will introduce differences between Python 3 and what may be more familiar. It’s a
reasonable test of whether you’re ready to move on to the advanced chapters in parts
3 and 4 of this book.
It’s possible that some readers, although new to Python, will have enough experience
with other programming languages to be able to pick up the bulk of what they
need to get going from chapter 3 and by browsing the Python standard library modules
listed in chapter 23 and the Python Library Reference in the Python documentation.

Table of Contents
preface xvii
acknowledgments xviii
about this book xx
PART 1 STARTING OUT
1 About Python 3
1.1 Why should I use Python? 3
1.2 What Python does well 4
Python is easy to use 4 ■ Python is expressive 4
Python is readable 5 ■ Python is complete—“batteries
included” 6 ■ Python is cross-platform 6 ■ Python is free 6
1.3 What Python doesn’t do as well 7
Python is not the fastest language 7 ■ Python doesn’t have the
most libraries 8 ■ Python doesn’t check variable types at
compile time 8
1.4 Why learn Python 3? 8
1.5 Summary 9
2 Getting started 10
2.1 Installing Python 10
2.2 IDLE and the basic interactive mode 12
The basic interactive mode 12 ■ The IDLE integrated development
environment 13 ■ Choosing between basic interactive mode and IDLE 14
2.3 Using IDLE’s Python Shell window 14
2.4 Hello, world 15
2.5 Using the interactive prompt to explore Python 15
2.6 Summary 17
3 The Quick Python overview 18
3.1 Python synopsis 19
3.2 Built-in data types 19
Numbers 19 ■ Lists 21 ■ Tuples 22 ■ Strings 23
Dictionaries 24 ■ Sets 24 ■ File objects 25
3.3 Control flow structures 25
Boolean values and expressions 25 ■ The if-elif-else
statement 26 ■ The while loop 26 ■ The for
loop 27 ■ Function definition 27 ■ Exceptions 28
3.4 Module creation 29
3.5 Object-oriented programming 30
3.6 Summary 31
PART 2 THE ESSENTIALS
4 The absolute basics 35
4.1 Indentation and block structuring 35
4.2 Differentiating comments 37
4.3 Variables and assignments 37
4.4 Expressions 38
4.5 Strings 39
4.6 Numbers 40
Built-in numeric functions 41 ■ Advanced numeric
functions 41 ■ Numeric computation 41 ■ Complex
numbers 41 ■ Advanced complex-number functions 42
4.7 The None value 43
4.8 Getting input from the user 43
4.9 Built-in operators 43
4.10 Basic Python style 43
4.11 Summary 44
5 Lists, tuples, and sets 45
5.1 Lists are like arrays 46
5.2 List indices 46
5.3 Modifying lists 48
5.4 Sorting lists 50
Custom sorting 51 ■ The sorted() function 52
5.5 Other common list operations 52
List membership with the in operator 52 ■ List concatenation
with the + operator 53 ■ List initialization with the *
operator 53 ■ List minimum or maximum with min and
max 53 ■ List search with index 53 ■ List matches with
count 54 ■ Summary of list operations 54
5.6 Nested lists and deep copies 55
5.7 Tuples 57
Tuple basics 57 ■ One-element tuples need a
comma 58 ■ Packing and unpacking tuples 58
Converting between lists and tuples 60
5.8 Sets 60
Set operations 60 ■ Frozensets 61
5.9 Summary 62
6 Strings 63
6.1 Strings as sequences of characters 63
6.2 Basic string operations 64
6.3 Special characters and escape sequences 64
Basic escape sequences 65 ■ Numeric (octal and hexadecimal) and
Unicode escape sequences 65 ■ Printing vs. evaluating strings
with special characters 66
6.4 String methods 67
The split and join string methods 67 ■ Converting strings to
numbers 68 ■ Getting rid of extra whitespace 69 ■ String
searching 70 ■ Modifying strings 71 ■ Modifying strings with
list manipulations 73 ■ Useful methods and constants 73
6.5 Converting from objects to strings 74
6.6 Using the format method 76
The format method and positional parameters 76 ■ The format
method and named parameters 76 ■ Format specifiers 77
6.7 Formatting strings with % 77
Using formatting sequences 78 ■ Named parameters and
formatting sequences 78
6.8 Bytes 80
6.9 Summary 80
7 Dictionaries 81
7.1 What is a dictionary? 82
Why dictionaries are called dictionaries 83
7.2 Other dictionary operations 83
7.3 Word counting 86
7.4 What can be used as a key? 86
7.5 Sparse matrices 88
7.6 Dictionaries as caches 88
7.7 Efficiency of dictionaries 89
7.8 Summary 89
8 Control flow 90
8.1 The while loop 90
The break and continue statements 91
8.2 The if-elif-else statement 91
8.3 The for loop 92
The range function 93 ■ Using break and continue in for
loops 94 ■ The for loop and tuple unpacking 94 ■ The
enumerate function 94 ■ The zip function 95
8.4 List and dictionary comprehensions 95
8.5 Statements, blocks, and indentation 96
8.6 Boolean values and expressions 99
Most Python objects can be used as Booleans 99 ■ Comparison and
Boolean operators 100
8.7 Writing a simple program to analyze a text file 101
8.8 Summary 102
9 Functions 103
9.1 Basic function definitions 103
9.2 Function parameter options 105
Positional parameters 105 ■ Passing arguments by parameter
name 106 ■ Variable numbers of arguments 107 ■ Mixing
argument-passing techniques 108
9.3 Mutable objects as arguments 108
9.4 Local, nonlocal, and global variables 109
9.5 Assigning functions to variables 111
9.6 lambda expressions 111
9.7 Generator functions 112
9.8 Decorators 113
9.9 Summary 114
10 Modules and scoping rules 115
10.1 What is a module? 115
10.2 A first module 116
10.3 The import statement 119
10.4 The module search path 119
Where to place your own modules 120
10.5 Private names in modules 121
10.6 Library and third-party modules 122
10.7 Python scoping rules and namespaces 123
10.8 Summary 128
11 Python programs 129
11.1 Creating a very basic program 130
Starting a script from a command line 130 ■ Command-line
arguments 131 ■ Redirecting the input and output of a
script 131 ■ The optparse module 132 ■ Using the fileinput
module 133
11.2 Making a script directly executable on UNIX 135
11.3 Scripts on Mac OS X 135
11.4 Script execution options in Windows 135
Starting a script as a document or shortcut 136 ■ Starting a script
from the Windows Run box 137 ■ Starting a script from a
command window 137 ■ Other Windows options 138
11.5 Scripts on Windows vs. scripts on UNIX 138
11.6 Programs and modules 140
11.7 Distributing Python applications 145
distutils 145 ■ py2exe and py2app 145 ■ Creating executable
programs with freeze 145
11.8 Summary 146
12 Using the filesystem 147
12.1 Paths and pathnames 148
Absolute and relative paths 148 ■ The current working
directory 149 ■ Manipulating pathnames 150 ■ Useful
constants and functions 153
12.2 Getting information about files 154
12.3 More filesystem operations 155
12.4 Processing all files in a directory subtree 156
12.5 Summary 157
13 Reading and writing files 159
13.1 Opening files and file objects 159
13.2 Closing files 160
13.3 Opening files in write or other modes 160
13.4 Functions to read and write text or binary data 161
Using binary mode 163
13.5 Screen input/output and redirection 163
13.6 Reading structured binary data with the struct module 165
13.7 Pickling objects into files 167
13.8 Shelving objects 170
13.9 Summary 171
14 Exceptions 172
14.1 Introduction to exceptions 173
General philosophy of errors and exception handling 173 ■ A more
formal definition of exceptions 175 ■ User-defined exceptions 176
14.2 Exceptions in Python 176
Types of Python exceptions 177 ■ Raising exceptions 178
Catching and handling exceptions 179 ■ Defining new
exceptions 180 ■ Debugging programs with the assert
statement 181 ■ The exception inheritance hierarchy 182
Example: a disk-writing program in Python 182 ■ Example:
exceptions in normal evaluation 183 ■ Where to use
exceptions 184
14.3 Using with 184
14.4 Summary 185
15 Classes and object-oriented programming 186
15.1 Defining classes 187
Using a class instance as a structure or record 187
15.2 Instance variables 188
15.3 Methods 188
15.4 Class variables 190
An oddity with class variables 191
15.5 Static methods and class methods 192
Static methods 192 ■ Class methods 193
15.6 Inheritance 194
15.7 Inheritance with class and instance variables 196
15.8 Private variables and private methods 197
15.9 Using @property for more flexible instance variables 198
15.10 Scoping rules and namespaces for class instances 199
15.11 Destructors and memory management 203
15.12 Multiple inheritance 207
15.13 Summary 208
16 Graphical user interfaces 209
16.1 Installing Tkinter 210
16.2 Starting Tk and using Tkinter 211
16.3 Principles of Tkinter 212
Widgets 212 ■ Named attributes 212 ■ Geometry management
and widget placement 213
16.4 A simple Tkinter application 214
16.5 Creating widgets 215
16.6 Widget placement 216
16.7 Using classes to manage Tkinter applications 218
16.8 What else can Tkinter do? 219
Event handling 220 ■ Canvas and text widgets 221
16.9 Alternatives to Tkinter 221
16.10 Summary 222
PART 3 ADVANCED LANGUAGE FEATURES
17 Regular expressions 225
17.1 What is a regular expression? 225
17.2 Regular expressions with special characters 226
17.3 Regular expressions and raw strings 227
Raw strings to the rescue 228
17.4 Extracting matched text from strings 229
17.5 Substituting text with regular expressions 232
17.6 Summary 233
18 Packages 234
18.1 What is a package? 234
18.2 A first example 235
18.3 A concrete example 236
Basic use of the mathproj package 237 ■ Loading subpackages
and submodules 238 ■ import statements within
packages 239 ■ __init__.py files in packages 239
18.4 The __all__ attribute 240
18.5 Proper use of packages 241
18.6 Summary 241
19 Data types as objects 242
19.1 Types are objects, too 242
19.2 Using types 243
19.3 Types and user-defined classes 243
19.4 Duck typing 245
19.5 Summary 246
20 Advanced object-oriented features 247
20.1 What is a special method attribute? 248
20.2 Making an object behave like a list 249
The __getitem__ special method attribute 249 ■ How it
works 250 ■ Implementing full list functionality 251
20.3 Giving an object full list capability 252
20.4 Subclassing from built-in types 254
Subclassing list 254 ■ Subclassing UserList 255
20.5 When to use special method attributes 256
20.6 Metaclasses 256
20.7 Abstract base classes 258
Using abstract base classes for type checking 259 ■ Creating
abstract base classes 260 ■ Using the @abstractmethod and
@abstractproperty decorators 260
20.8 Summary 262
PART 4 WHERE CAN YOU GO FROM HERE? 
21 Testing your code made easy(-er) 265
21.1 Why you need to have tests 265
21.2 The assert statement 266
Python’s __debug__ variable 266
21.3 Tests in docstrings: doctests 267
Avoiding doctest traps 269 ■ Tweaking doctests with
directives 269 ■ Pros and cons of doctests 270
21.4 Using unit tests to test everything, every time 270
Setting up and running a single test case 270 ■ Running the
test 272 ■ Running multiple tests 272 ■ Unit tests vs.
doctests 273
21.5 Summary 273
22 Moving from Python 2 to Python 3 274
22.1 Porting from 2 to 3 274
Steps in porting from Python 2.x to 3.x 275
22.2 Testing with Python 2.6 and -3 276
22.3 Using 2to3 to convert the code 277
22.4 Testing and common problems 279
22.5 Using the same code for 2 and 3 280
Using Python 2.5 or earlier 280 ■ Writing for Python 3.x and
converting back 281
22.6 Summary 281
23 Using Python libraries 282
23.1 “Batteries included”—the standard library 282
Managing various data types 283 ■ Manipulating files and
storage 284 ■ Accessing operating system services 285 ■ Using
internet protocols and formats 286 ■ Development and debugging
tools and runtime services 286
23.2 Moving beyond the standard library 287
23.3 Adding more Python libraries 287
23.4 Installing Python libraries using setup.py 288
Installing under the home scheme 288 ■ Other installation
options 289
23.5 PyPI, a.k.a. “the Cheese Shop” 289
23.6 Summary 289
24 Network, web, and database programming 290
24.1 Accessing databases in Python 291
Using the sqlite3 database 291
24.2 Network programming in Python 293
Creating an instant HTTP server 293 ■ Writing an HTTP
client 294
24.3 Creating a Python web application 295
Using the web server gateway interface 295 ■ Using the wsgi
library to create a basic web app 295 ■ Using frameworks to create
advanced web apps 296
24.4 Sample project—creating a message wall 297
Creating the database 297 ■ Creating an application
object 298 ■ Adding a form and retrieving its contents
298 ■ Saving the form’s contents 299 ■ Parsing the URL and
retrieving messages 300 ■ Adding an HTML wrapper 303
24.5 Summary 304
appendix 305
index 323

Bookscreen
e-books shop

preface
I’ve been coding in Python for a number of years, longer than any other language I’ve
ever used. I use Python for system administration, for web applications, for database
management, and sometimes just to help myself think clearly.

To be honest, I’m sometimes a little surprised that Python has worn so well. Based
on my earlier experience, I would have expected that by now some other language
would have come along that was faster, cooler, sexier, whatever. Indeed, other languages
have come along, but none that helped me do what I needed to do quite as
effectively as Python. In fact, the more I use Python and the more I understand it, the
more I feel the quality of my programming improve and mature.

This is a second edition, and my mantra in updating has been, “If it ain’t broke,
don’t fix it.” Much of the content has been freshened for Python 3 but is largely as
written in the first edition. Of course, the world of Python has changed since Python
1.5, so in several places I’ve had to make significant changes or add new material. On
those occasions I’ve done my best to make the new material compatible with the clear
and low-key style of the original.

For me, the aim of this book is to share the positive experiences I’ve gotten from
coding in Python by introducing people to Python 3, the latest and, in my opinion,
the best version of Python to date. May your journey be as satisfying as mine has been.

0