Docsity

Programming in Python 3, 2nd Edition, Notas de estudo de Informática

Toggle sidebar
bg1
Programming in Python 3
A Complete Introduction to the Python Language
Second Edition
Mark Summerfield
Upper Saddle River, NJ ·Boston ·Indianapolis ·San Francisco
New York ·Toronto ·Montreal ·London ·Munich ·Paris ·Madrid
Capetown ·Sydney ·Tokyo ·Singapore ·Mexico City
www.it-ebooks.info
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe Programming in Python 3, 2nd Edition e outras Notas de estudo em PDF para Informática, somente na Docsity!

Programming in Python 3

A Complete Introduction to the Python Language

Second Edition

Mark Summerfield

Upper Saddle River, NJ · Boston · Indianapolis · San Francisco
New York · Toronto · Montreal · London · Munich · Paris · Madrid
Capetown · Sydney · Tokyo · Singapore · Mexico City

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.

The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.

The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact:

U.S. Corporate and Government Sales (800) 382- [email protected]

For sales outside the United States, please contact:

International Sales [email protected]

Visit us on the Web: informit.com/aw

Library of Congress Cataloging-in-Publication Data

Summerfield, Mark. Programming in Python 3 : a complete introduction to the Python language / Mark Summerfield.—2nd ed. p. cm. Includes bibliographical references and index. ISBN 978-0-321-68056-3 (pbk. : alk. paper)

  1. Python (Computer program language) 2. Object-oriented programming (Computer science) I. Title. QA76.73.P98S86 2010 005.13’3—dc 2009035430

Copyright © 2010 Pearson Education, Inc.

All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to:

Pearson Education, Inc. Rights and Contracts Department 501 Boylston Street, Suite 900 Boston, MA 02116 Fax: (617) 671-

ISBN-13: 978-0-321-68056- ISBN-10: 0-321-68056- Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana. First printing, November 2009

Contents

  • Introduction Listof Tables xv
  • Chapter1. RapidIntroductiontoProceduralProgramming
  • Chapter2. DataTypes
  • Chapter3. CollectionDataTypes
  • Chapter4. ControlStructuresandFunctions
  • Chapter5. Modules
  • Chapter6. Object-OrientedProgramming
  • Chapter7. FileHandling
  • Chapter8. AdvancedProgrammingTechniques
  • Chapter9. Debugging,Testing,andProfiling
  • Chapter10. ProcessesandThreading
  • Chapter11. Networking
  • Chapter12. DatabaseProgramming
  • Chapter13. RegularExpressions
  • Chapter14. IntroductiontoParsing
  • Chapter15. IntroductiontoGUIProgramming
  • Epilogue
  • SelectedBibliography
  • Index
  • Introduction List of Tables xv
  • Chapter 1 Rapid Introduction to Procedural Programming
  • Creating and Running Python Programs
  • Python’s “Beautiful Heart”
  • Piece #1: Data Types
  • Piece #2: Object References
  • Piece #3: Collection Data Types
  • Piece #4: Logical Operations
  • Piece #5: Control Flow Statements
  • Piece #6: Arithmetic Operators
  • Piece #7: Input/Output
  • Piece #8: Creating and Calling Functions
  • Examples
  • bigdigits.py
  • generate_grid.py
  • Summary
  • Exercises
  • Chapter 2 Data Types
  • Identifiers and Keywords
  • Integral Types
  • Integers
  • Booleans
  • Floating-Point Types
  • Floating-Point Numbers
  • Complex Numbers
  • Decimal Numbers
  • Strings
  • Comparing Strings
  • Slicing and Striding Strings
  • String Operators and Methods
  • String Formatting with the str.format() Method
  • Character Encodings
  • Examples
  • quadratic.py
  • csv2html.py
  • Summary
  • Exercises
  • Chapter 3 Collection Data Types
  • Sequence Types
  • Tuples
  • Named Tuples
  • Lists
  • Set Types
  • Sets
  • Frozen Sets
  • Mapping Types
  • Dictionaries
  • Default Dictionaries
  • Ordered Dictionaries
  • Iterating and Copying Collections
  • Iterators and Iterable Operations and Functions
  • Copying Collections
  • Examples
  • generate_usernames.py
  • statistics.py
  • Summary
  • Exercises
  • Chapter 4 Control Structures and Functions
  • Control Structures
  • Conditional Branching
  • Looping
  • Exception Handling
  • Catching and Raising Exceptions
  • Custom Exceptions
  • Custom Functions
  • Names and Docstrings
  • Argument and Parameter Unpacking
  • Accessing Variables in the Global Scope
  • Lambda Functions
  • Assertions
  • Example: make_html_skeleton.py
  • Summary
  • Exercise
  • Chapter 5 Modules
  • Modules and Packages
  • Packages
  • Custom Modules
  • Overview of Python’s Standard Library
  • String Handling
  • Command-Line Programming
  • Mathematics and Numbers
  • Times and Dates
  • Algorithms and Collection Data Types
  • File Formats, Encodings, and Data Persistence
  • File, Directory, and Process Handling
  • Networking and Internet Programming
  • XML
  • Other Modules
  • Summary
  • Exercise
  • Chapter 6 Object-Oriented Programming
  • The Object-Oriented Approach
  • Object-Oriented Concepts and Terminology
  • Custom Classes
  • Attributes and Methods
  • Inheritance and Polymorphism
  • Using Properties to Control Attribute Access
  • Creating Complete Fully Integrated Data Types
  • Custom Collection Classes
  • Creating Classes That Aggregate Collections
  • Creating Collection Classes Using Aggregation
  • Creating Collection Classes Using Inheritance
  • Summary
  • Exercises
  • Chapter 7 File Handling
  • Writing and Reading Binary Data
  • Pickles with Optional Compression
  • Raw Binary Data with Optional Compression
  • Writing and Parsing Text Files
  • Writing Text
  • Parsing Text
  • Parsing Text Using Regular Expressions
  • Writing and Parsing XML Files
  • Element Trees
  • DOM (Document Object Model)
  • Manually Writing XML
  • Parsing XML with SAX (Simple API for XML)
  • Random Access Binary Files
  • A Generic BinaryRecordFile Class
  • Example: The BikeStock Module’s Classes
  • Summary
  • Exercises
  • Chapter 8 Advanced Programming Techniques
  • Further Procedural Programming
  • Branching Using Dictionaries
  • Generator Expressions and Functions
  • Dynamic Code Execution and Dynamic Imports
  • Local and Recursive Functions
  • Function and Method Decorators
  • Function Annotations
  • Further Object-Oriented Programming
  • Controlling Attribute Access
  • Functors
  • Context Managers
  • Descriptors
  • Class Decorators
  • Abstract Base Classes
  • Multiple Inheritance
  • Metaclasses
  • Functional-Style Programming
  • Partial Function Application
  • Coroutines
  • Example: Valid.py
  • Summary
  • Exercises
  • Chapter 9 Debugging, Testing, and Profiling
  • Debugging
  • Dealing with Syntax Errors
  • Dealing with Runtime Errors
  • Scientific Debugging
  • Unit Testing
  • Profiling
  • Summary
  • Chapter 10 Processes and Threading
  • Using the Multiprocessing Module
  • Using the Threading Module
  • Example: A Threaded Find Word Program
  • Example: A Threaded Find Duplicate Files Program
  • Summary
  • Exercises
  • Chapter 11 Networking
  • Creating a TCP Client
  • Creating a TCP Server
  • Summary
  • Exercises
  • Chapter 12 Database Programming
  • DBM Databases
  • SQL Databases
  • Summary
  • Exercise
  • Chapter 13 Regular Expressions
  • Python’s Regular Expression Language
  • Characters and Character Classes
  • Quantifiers
  • Grouping and Capturing
  • Assertions and Flags
  • The Regular Expression Module
  • Summary
  • Exercises
  • Chapter 14 Introduction to Parsing
  • BNF Syntax and Parsing Terminology
  • Writing Handcrafted Parsers
  • Simple Key–Value Data Parsing
  • Playlist Data Parsing
  • Parsing the Blocks Domain-Specific Language
  • Pythonic Parsing with PyParsing
  • A Quick Introduction to PyParsing
  • Simple Key–Value Data Parsing
  • Playlist Data Parsing
  • Parsing the Blocks Domain-Specific Language
  • Parsing First-Order Logic
  • Lex/Yacc-Style Parsing with PLY
  • Simple Key–Value Data Parsing
  • Playlist Data Parsing
  • Parsing the Blocks Domain-Specific Language
  • Parsing First-Order Logic
  • Summary
  • Exercise
  • Chapter 15 Introduction to GUI Programming
  • Dialog-Style Programs
  • Main-Window-Style Programs
  • Creating a Main Window
  • Creating a Custom Dialog
  • Summary
  • Exercises
  • Epilogue
  • Selected Bibliography
  • Index
  • 2.1. Python’s Keywords List of Tables
  • 2.2. Numeric Operators and Functions
  • 2.3. Integer Conversion Functions
  • 2.4. Integer Bitwise Operators
  • 2.5. The Math Module’s Functions and Constants #1
  • 2.6. The Math Module’s Functions and Constants #2
  • 2.7. Python’s String Escapes
  • 2.8. String Methods #1
  • 2.9. String Methods #2
  • 2.10. String Methods #3
  • 3.1. List Methods
  • 3.2. Set Methods and Operators
  • 3.3. Dictionary Methods
  • 3.4. Common Iterable Operators and Functions
  • 6.1. Comparison Special Methods
  • 6.2. Fundamental Special Methods
  • 6.3. Numeric and Bitwise Special Methods
  • 6.4. Collection Special Methods
  • 7.1. Bytes and Bytearray Methods #1
  • 7.2. Bytes and Bytearray Methods #2
  • 7.3. Bytes and Bytearray Methods #3
  • 7.4. File Object Attributes and Methods #1
  • 7.5. File Object Attributes and Methods #2
  • 8.1. Dynamic Programming and Introspection Functions
  • 8.2. Attribute Access Special Methods
  • 8.3. The Numbers Module’s Abstract Base Classes
  • 8.4. The Collections Module’s Main Abstract Base Classes
  • 12.1. DB-API 2.0 Connection Object Methods
  • 12.2. DB-API 2.0 Cursor Object Attributes and Methods
  • 13.1. Character Class Shorthands
  • 13.2. Regular Expression Quantifiers
  • 13.3. Regular Expression Assertions
  • 13.4. The Regular Expression Module’s Functions
  • 13.5. The Regular Expression Module’s Flags
  • 13.6. Regular Expression Object Methods
  • 13.7. Match Object Attributes and Methods

2 Introduction

The book’s aim is to teach the Python language , and although many of the standard Python libraries are used, not all of them are. This is not a problem, because once you have read the book, you will have enough Python knowledge to be able to make use of any of the standard libraries, or any third-party Python library, and be able to create library modules of your own.

The book is designed to be useful to several different audiences, including self- taught and hobbyist programmers, students, scientists, engineers, and others who need to program as part of their work, and of course, computing profes- sionals and computer scientists. To be of use to such a wide range of people without boring the knowledgeable or losing the less-experienced, the book as- sumes at least some programming experience (in any language). In particu- lar, it assumes a basic knowledge of data types (such as numbers and strings), collection data types (such as sets and lists), control structures (such as if and while statements), and functions. In addition, some examples and exercises assume a basic knowledge of HTML markup, and some of the more specialized chapters at the end assume a basic knowledge of their subject area; for exam- ple, the databases chapter assumes a basic knowledge of SQL.

The book is structured in such a way as to make you as productive as possible as quickly as possible. By the end of the first chapter you will be able to write small but useful Python programs. Each successive chapter introduces new topics, and often both broadens and deepens the coverage of topics introduced in earlier chapters. This means that if you read the chapters in sequence, you can stop at any point and you’ll be able to write complete programs with what you have learned up to that point, and then, of course, resume reading to learn more advanced and sophisticated techniques when you are ready. For this reason, some topics are introduced in one chapter, and then are explored further in one or more later chapters.

Two key problems arise when teaching a new programming language. The first is that sometimes when it is necessary to teach one particular concept, that concept depends on another concept, which in turn depends either directly or indirectly on the first. The second is that, at the beginning, the reader may know little or nothing of the language, so it is very difficult to present inter- esting or useful examples and exercises. In this book, we seek to solve both of these problems, first by assuming some prior programming experience, and second by presenting Python’s “beautiful heart” in Chapter 1—eight key pieces of Python that are sufficient on their own to write decent programs. One con- sequence of this approach is that in the early chapters some of the examples are a bit artificial in style, since they use only what has been taught up to the point where they are presented; this effect diminishes chapter by chapter, until by the end of Chapter 7, all the examples are written in completely natural and idiomatic Python 3 style.

The book’s approach is wholly practical, and you are encouraged to try out the examples and exercises for yourself to get hands-on experience. Wherever

Introduction 3

possible, small but complete programs and modules are used as examples to provide realistic use cases. The examples, exercise solutions, and the book’s errata are available online at www.qtrac.eu/py3book.html.

Two sets of examples are provided. The standard examples work with any Python 3. x version—use these if you care about Python 3.0 compatibility. The “eg31” examples work with Python 3.1 or later—use these if you don’t need to support Python 3.0 because your programs’ users have Python 3.1 or later. All of the examples have been tested on Windows, Linux, and Mac OS X.

While it is best to use the most recent version of Python 3, this is not always possible if your users cannot or will not upgrade. Every example in this book works with Python 3.0 except where stated, and those examples and features that are specific to Python 3.1 are clearly indicated as such.

Although it is possible to use this book to develop software that uses only Python 3.0, for those wanting to produce software that is expected to be in use for many years and that is expected to be compatible with later Python 3. x re- leases, it is best to use Python 3.1 as the oldest Python 3 version that you sup- port. This is partly because Python 3.1 has some very nice new features, but mostly because the Python developers strongly recommend using Python 3. (or later). The developers have decided that Python 3.0.1 will be the last Python 3.0. y release, and that there will be no more Python 3.0. y releases even if bugs or security problems are discovered. Instead, they want all Python 3 users to migrate to Python 3.1 (or to a later version), which will have the usu- al bugfix and security maintenance releases that Python versions normal- ly have.

The Structure of the Book

Chapter 1 presents eight key pieces of Python that are sufficient for writing complete programs. It also describes some of the Python programming environments that are available and presents two tiny example programs, both built using the eight key pieces of Python covered earlier in the chapter.

Chapters 2 through 5 introduce Python’s procedural programming features, including its basic data types and collection data types, and many useful built- in functions and control structures, as well as very simple text file handling. Chapter 5 shows how to create custom modules and packages and provides an overview of Python’s standard library so that you will have a good idea of the functionality that Python provides out of the box and can avoid reinventing the wheel.

Chapter 6 provides a thorough introduction to object-oriented programming with Python. All of the material on procedural programming that you learned in earlier chapters is still applicable, since object-oriented programming is

Introduction 5

typing python3 -V, and if that does not work try python3.0 -V, and failing that try python3.1 -V. If any of these work you now know that you already have Python installed, what version it is, and what it is called. (In this book we use the name python3, but use whatever name worked for you, for example, python3.1.) If you don’t have any version of Python 3 installed, read on.

For Windows and Mac OS X, easy-to-use graphical installer packages are pro- vided that take you step-by-step through the installation process. These are available from www.python.org/download. For Windows, download the “Windows x86 MSI Installer”, unless you know for sure that your machine has a different processor for which a separate installer is supplied—for example, if you have an AMD64, get the “Windows AMD64 MSI Installer”. Once you’ve got the in- staller, just run it and follow the on-screen instructions.

For Linux, BSD, and other Unixes (apart from Mac OS X for which a .dmg in- stallation file is provided), the easiest way to install Python is to use your oper- ating system’s package management system. In most cases Python is provided in several separate packages. For example, in Ubuntu (from version 8), there is python3.0 for Python, idle-python3.0 for IDLE (a simple development envi- ronment), and python3.0-doc for the documentation—as well as many other packages that provide add-ons for even more functionality than that provided by the standard library. (Naturally, the package names will start with python- 3.1 for the Python 3.1 versions, and so on.)

If no Python 3 packages are available for your operating system you will need to download the source from www.python.org/download and build Python from scratch. Get either of the source tarballs and unpack it using tar xvfz Python-3.1.tgz if you got the gzipped tarball or tar xvfj Python-3.1.tar.bz2 if you got the bzip2 tarball. (The version numbers may be different, for example, Python-3.1.1.tgz or Python-3.1.2.tar.bz2, in which case simply replace 3.1 with your actual version number throughout.) The configuration and building are standard. First, change into the newly created Python-3.1 directory and run ./configure. (You can use the --prefix option if you want to do a local install.) Next, run make.

It is possible that you may get some messages at the end saying that not all modules could be built. This normally means that you don’t have some of the required libraries or headers on your machine. For example, if the readline module could not be built, use the package management system to install the corresponding development library; for example, readline-devel on Fedora- based systems and readline-dev on Debian-based systems such as Ubuntu. Another module that may not build straight away is the tkinter module—this depends on both the Tcl and Tk development libraries, tcl-devel and tk-devel on Fedora-based systems, and tcl8.5-dev and tk8.5-dev on Debian-based sys- tems (and where the minor version may not be 5). Unfortunately, the relevant package names are not always so obvious, so you might need to ask for help on

6 Introduction

Python’s mailing list. Once the missing packages are installed, run ./configure and make again.

After successfully making, you could run make test to see that everything is okay, although this is not necessary and can take many minutes to complete.

If you used --prefix to do a local installation, just run make install. For Python 3.1, if you installed into, say, ~/local/python31, then by adding the ~/lo- cal/python31/bin directory to your PATH, you will be able to run Python using python3 and IDLE using idle3. Alternatively, if you already have a local directo- ry for executables that is already in your PATH (such as ~/bin), you might prefer to add soft links instead of changing the PATH. For example, if you keep exe- cutables in ~/bin and you installed Python in ~/local/python31, you could create suitable links by executing ln -s ~/local/python31/bin/python3 ~/bin/python3, and ~/local/python31/bin/idle3 ~/bin/idle3. For this book we did a local install and added soft links on Linux and Mac OS X exactly as described here—and on Windows we used the binary installer.

If you did not use --prefix and have root access, log in as root and do make in- stall. On sudo-based systems like Ubuntu, do sudo make install. If Python 2 is on the system, /usr/bin/python won’t be changed, and Python 3 will be avail- able as python3.0 (or python3.1 depending on the version installed) and from Python 3.1, in addition, as python3. Python 3.0’s IDLE is installed as idle, so if access to Python 2’s IDLE is still required the old IDLE will need to be renamed—for example, to /usr/bin/idle2— before doing the install. Python 3. installs IDLE as idle3 and so does not conflict with Python 2’s IDLE.

Acknowledgments

I would first like to acknowledge with thanks the feedback I have received from readers of the first edition, who gave corrections, or made suggestions, or both.

My next acknowledgments are of the book’s technical reviewers, starting with Jasmin Blanchette, a computer scientist, programmer, and writer with whom I have cowritten two C++/Qt books. Jasmin’s involvement with chapter planning and his suggestions and criticisms regarding all the examples, as well as his careful reading, have immensely improved the quality of this book.

Georg Brandl is a leading Python developer and documentor responsible for creating Python’s new documentation tool chain. Georg spotted many sub- tle mistakes and very patiently and persistently explained them until they were understood and corrected. He also made many improvements to the ex- amples.

Rapid Introduction to

Procedural Programming

||||

● Creating and Running Python Programs ● Python’s “Beautiful Heart”

This chapter provides enough information to get you started writing Python programs. We strongly recommend that you install Python if you have not already done so, so that you can get hands-on experience to reinforce what you learn here. (The Introduction explains how to obtain and install Python on all major platforms; 4 ➤.)

This chapter’s first section shows you how to create and execute Python pro- grams. You can use your favorite plain text editor to write your Python code, but the IDLE programming environment discussed in this section provides not only a code editor, but also additional functionality, including facilities for ex- perimenting with Python code, and for debugging Python programs.

The second section presents eight key pieces of Python that on their own are sufficient to write useful programs. These pieces are all covered fully in later chapters, and as the book progresses they are supplemented by all of the rest of Python so that by the end of the book, you will have covered the whole language and will be able to use all that it offers in your programs.

The chapter’s final section introduces two short programs which use the subset of Python features introduced in the second section so that you can get an immediate taste of Python programming.

Creating and Running Python Programs (^) |||

Python code can be written using any plain text editor that can load and save text using either the ASCII or the UTF-8 Unicode character Char- acter encod- ings ➤ 91

encoding. By de- fault, Python files are assumed to use the UTF-8 character encoding, a super- set of ASCII that can represent pretty well every character in every language. Python files normally have an extension of .py, although on some Unix-like sys-

10 Chapter 1. Rapid Introduction to Procedural Programming

tems (e.g., Linux and Mac OS X) some Python applications have no extension, and Python GUI (Graphical User Interface) programs usually have an exten- sion of .pyw, particularly on Windows and Mac OS X. In this book we always use an extension of .py for Python console programs and Python modules, and .pyw for GUI programs. All the examples presented in this book run unchanged on all platforms that have Python 3 available.

Just to make sure that everything is set up correctly, and to show the clas- sical first example, create a file called hello.py in a plain text editor (Win- dows Notepad is fine—we’ll use a better editor shortly), with the following contents:

#!/usr/bin/env python print("Hello", "World!")

The first line is a comment. In Python, comments begin with a (^) # and continue to the end of the line. (We will explain the rather cryptic comment in a moment.) The second line is blank—outside quoted strings, Python ignores blank lines, but they are often useful to humans to break up large blocks of code to make them easier to read. The third line is Python code. Here, the (^) print() function is called with two arguments, each of type (^) str (string; i.e., a sequence of char- acters).

Each statement encountered in a (^) .py file is executed in turn, starting with the first one and progressing line by line. This is different from some other languages, for example, C++ and Java, which have a particular function or method with a special name where they start from. The flow of control can of course be diverted as we will see when we discuss Python’s control structures in the next section.

We will assume that Windows users keep their Python code in the (^) C:\py3eg directory and that Unix (i.e., Unix, Linux, and Mac OS X) users keep their code in the (^) $HOME/py3eg directory. Save (^) hello.py into the (^) py3eg directory and close the text editor.

Now that we have a program, we can run it. Python programs are executed by the Python interpreter, and normally this is done inside a console window. On Windows the console is called “Console”, or “DOS Prompt”, or “MS-DOS Prompt”, or something similar, and is usually available from Start→All Pro- grams→Accessories. On Mac OS X the console is provided by the Terminal.app pro- gram (located in (^) Applications/Utilities by default), available using Finder, and on other Unixes, we can use an (^) xterm or the console provided by the windowing environment, for example, (^) konsole or (^) gnome-terminal.

Start up a console, and on Windows enter the following commands (which assume that Python is installed in the default location)—the console’s output is shown in (^) lightface; what you type is shown in (^) bold :