logo资料库

The Quick Python Book, 3rd Edition (True PDF).pdf

第1页 / 共473页
第2页 / 共473页
第3页 / 共473页
第4页 / 共473页
第5页 / 共473页
第6页 / 共473页
第7页 / 共473页
第8页 / 共473页
资料共473页,剩余部分请下载后查看
The Quick Python Book
brief contents
contents
foreword
preface
acknowledgments
about this book
How to use this book
Roadmap
Code conventions
Exercises
Exercise answers
Source code downloads
System requirements
Software requirements
Book forum
About the author
about the cover illustration
Part 1 Starting out
1 About Python
1.1 Why should I use Python?
1.2 What Python does well
1.2.1 Python is easy to use
1.2.2 Python is expressive
1.2.3 Python is readable
1.2.4 Python is complete??batteries included?
1.2.5 Python is cross-platform
1.2.6 Python is free
1.3 What Python doesn?t do as well
1.3.1 Python isn?t the fastest language
1.3.2 Python doesn?t have the most libraries
1.3.3 Python doesn?t check variable types at compile time
1.3.4 Python doesn?t have much mobile support
1.3.5 Python doesn?t use multiple processors well
1.4 Why learn Python 3?
Summary
2 Getting started
2.1 Installing Python
2.2 Basic interactive mode and IDLE
2.2.1 The basic interactive mode
2.2.2 The IDLE integrated development environment
2.2.3 Choosing between basic interactive mode and IDLE
2.3 Using IDLE?s Python shell window
2.4 Hello, world
2.5 Using the interactive prompt to explore Python
Summary
3 The Quick Python overview
3.1 Python synopsis
3.2 Built-in data types
3.2.1 Numbers
3.2.2 Lists
3.2.3 Tuples
3.2.4 Strings
3.2.5 Dictionaries
3.2.6 Sets
3.2.7 File objects
3.3 Control flow structures
3.3.1 Boolean values and expressions
3.3.2 The if-elif-else statement
3.3.3 The while loop
3.3.4 The for loop
3.3.5 Function definition
3.3.6 Exceptions
3.3.7 Context handling using the with keyword
3.4 Module creation
3.5 Object-oriented programming
Summary
Part 2 The essentials
4 The absolute basics
4.1 Indentation and block structuring
4.2 Differentiating comments
4.3 Variables and assignments
4.4 Expressions
4.5 Strings
4.6 Numbers
4.6.1 Built-in numeric functions
4.6.2 Advanced numeric functions
4.6.3 Numeric computation
4.6.4 Complex numbers
4.6.5 Advanced complex-number functions
4.7 The None value
4.8 Getting input from the user
4.9 Built-in operators
4.10 Basic Python style
Summary
5 Lists, tuples, and sets
5.1 Lists are like arrays
5.2 List indices
5.3 Modifying lists
5.4 Sorting lists
5.4.1 Custom sorting
5.4.2 The sorted() function
5.5 Other common list operations
5.5.1 List membership with the in operator
5.5.2 List concatenation with the + operator
5.5.3 List initialization with the * operator
5.5.4 List minimum or maximum with min and max
5.5.5 List search with index
5.5.6 List matches with count
5.5.7 Summary of list operations
5.6 Nested lists and deep copies
5.7 Tuples
5.7.1 Tuple basics
5.7.2 One-element tuples need a comma
5.7.3 Packing and unpacking tuples
5.7.4 Converting between lists and tuples
5.8 Sets
5.8.1 Set operations
5.8.2 Frozensets
Summary
6 Strings
6.1 Strings as sequences of characters
6.2 Basic string operations
6.3 Special characters and escape sequences
6.3.1 Basic escape sequences
6.3.2 Numeric (octal and hexadecimal) and Unicode escape sequences
6.3.3 Printing vs. evaluating strings with special characters
6.4 String methods
6.4.1 The split and join string methods
6.4.2 Converting strings to numbers
6.4.3 Getting rid of extra whitespace
6.4.4 String searching
6.4.5 Modifying strings
6.4.6 Modifying strings with list manipulations
6.4.7 Useful methods and constants
6.5 Converting from objects to strings
6.6 Using the format method
6.6.1 The format method and positional parameters
6.6.2 The format method and named parameters
6.6.3 Format specifiers
6.7 Formatting strings with %
6.7.1 Using formatting sequences
6.7.2 Named parameters and formatting sequences
6.8 String interpolation
6.9 Bytes
Summary
7 Dictionaries
7.1 What is a dictionary?
7.2 Other dictionary operations
7.3 Word counting
7.4 What can be used as a key?
7.5 Sparse matrices
7.6 Dictionaries as caches
7.7 Efficiency of dictionaries
Summary
8 Control flow
8.1 The while loop
8.2 The if-elif-else statement
8.3 The for loop
8.3.1 The range function
8.3.2 Controlling range with starting and stepping values
8.3.3 Using break and continue in for loops
8.3.4 The for loop and tuple unpacking
8.3.5 The enumerate function
8.3.6 The zip function
8.4 List and dictionary comprehensions
8.4.1 Generator expressions
8.5 Statements, blocks, and indentation
8.6 Boolean values and expressions
8.6.1 Most Python objects can be used as Booleans
8.6.2 Comparison and Boolean operators
8.7 Writing a simple program to analyze a text file
Summary
9 Functions
9.1 Basic function definitions
9.2 Function parameter options
9.2.1 Positional parameters
9.2.2 Passing arguments by parameter name
9.2.3 Variable numbers of arguments
9.2.4 Mixing argument-passing techniques
9.3 Mutable objects as arguments
9.4 Local, nonlocal, and global variables
9.5 Assigning functions to variables
9.6 lambda expressions
9.7 Generator functions
9.8 Decorators
Summary
10 Modules and scoping rules
10.1 What is a module?
10.2 A first module
10.3 The import statement
10.4 The module search path
10.4.1 Where to place your own modules
10.5 Private names in modules
10.6 Library and third-party modules
10.7 Python scoping rules and namespaces
Summary
11 Python programs
11.1 Creating a very basic program
11.1.1 Starting a script from a command line
11.1.2 Command-line arguments
11.1.3 Redirecting the input and output of a script
11.1.4 The argparse module
11.1.5 Using the fileinput module
11.2 Making a script directly executable on UNIX
11.3 Scripts on macOS
11.4 Script execution options in Windows
11.4.1 Starting a script from a command window or PowerShell
11.4.2 Other Windows options
11.5 Programs and modules
11.6 Distributing Python applications
11.6.1 Wheels packages
11.6.2 zipapp and pex
11.6.3 py2exe and py2app
11.6.4 Creating executable programs with freeze
Summary
12 Using the filesystem
12.1 os and os.path vs. pathlib
12.2 Paths and pathnames
12.2.1 Absolute and relative paths
12.2.2 The current working directory
12.2.3 Accessing directories with pathlib
12.2.4 Manipulating pathnames
12.2.5 Manipulating pathnames with pathlib
12.2.6 Useful constants and functions
12.3 Getting information about files
12.3.1 Getting information about files with scandir
12.4 More filesystem operations
12.4.1 More filesystem operations with pathlib
12.5 Processing all files in a directory subtree
Summary
13 Reading and writing files
13.1 Opening files and file objects
13.2 Closing files
13.3 Opening files in write or other modes
13.4 Functions to read and write text or binary data
13.4.1 Using binary mode
13.5 Reading and writing with pathlib
13.6 Screen input/output and redirection
13.7 Reading structured binary data with the struct module
13.8 Pickling objects files
13.8.1 Reasons not to pickle
13.9 Shelving objects
Summary
14 Exceptions
14.1 Introduction to exceptions
14.1.1 General philosophy of errors and exception handling
14.1.2 A more formal definition of exceptions
14.1.3 Handling different types of exceptions
14.2 Exceptions in Python
14.2.1 Types of Python exceptions
14.2.2 Raising exceptions
14.2.3 Catching and handling exceptions
14.2.4 Defining new exceptions
14.2.5 Debugging programs with the assert statement
14.2.6 The exception inheritance hierarchy
14.2.7 Example: a disk-writing program in Python
14.2.8 Example: exceptions in normal evaluation
14.2.9 Where to use exceptions
14.3 Context managers using the with keyword
Summary
Part 3 Advanced language features
15 Classes and object-oriented programming
15.1 Defining classes
15.1.1 Using a class instance as a structure or record
15.2 Instance variables
15.3 Methods
15.4 Class variables
15.4.1 An oddity with class variables
15.5 Static methods and class methods
15.5.1 Static methods
15.5.2 Class methods
15.6 Inheritance
15.7 Inheritance with class and instance variables
15.8 Recap: Basics of Python classes
15.9 Private variables and private methods
15.10 Using @property for more flexible instance variables
15.11 Scoping rules and namespaces for class instances
15.12 Destructors and memory management
15.13 Multiple inheritance
Summary
16 Regular expressions
16.1 What is a regular expression?
16.2 Regular expressions with special characters
16.3 Regular expressions and raw strings
16.3.1 Raw strings to the rescue
16.4 Extracting matched text from strings
16.5 Substituting text with regular expressions
Summary
17 Data types as objects
17.1 Types are objects, too
17.2 Using types
17.3 Types and user-defined classes
17.4 Duck typing
17.5 What is a special method attribute?
17.6 Making an object behave like a list
17.7 The __getitem__ special method attribute
17.7.1 How it works
17.7.2 Implementing full list functionality
17.8 Giving an object full list capability
17.9 Subclassing from built-in types
17.9.1 Subclassing list
17.9.2 Subclassing UserList
17.10 When to use special method attributes
Summary
18 Packages
18.1 What is a package?
18.2 A first example
18.3 A concrete example
18.3.1 __init__.py files in packages
18.3.2 Basic use of the mathproj package
18.3.3 Loading subpackages and submodules
18.3.4 import statements within packages
18.4 The __all__ attribute
18.5 Proper use of packages
Summary
19 Using Python libraries
19.1 ?Batteries included?: The standard library
19.1.1 Managing various data types
19.1.2 Manipulating files and storage
19.1.3 Accessing operating system services
19.1.4 Using internet protocols and formats
19.1.5 Development and debugging tools and runtime services
19.2 Moving beyond the standard library
19.3 Adding more Python libraries
19.4 Installing Python libraries using pip and venv
19.4.1 Installing with the ?user flag
19.4.2 Virtual environments
19.5 PyPI (a.k.a. ?The Cheese Shop?)
Summary
Part 4 Working with data
20 Basic file wrangling
20.1 The problem: The never-ending flow of data files
20.2 Scenario: The product feed from hell
20.3 More organization
20.4 Saving storage space: Compression and grooming
20.4.1 Compressing files
20.4.2 Grooming files
Summary
21 Processing data files
21.1 Welcome to ETL
21.2 Reading text files
21.2.1 Text encoding: ASCII, Unicode, and others
21.2.2 Unstructured text
21.2.3 Delimited flat files
21.2.4 The csv module
21.2.5 Reading a csv file as a list of dictionaries
21.3 Excel files
21.4 Data cleaning
21.4.1 Cleaning
21.4.2 Sorting
21.4.3 Data cleaning issues and pitfalls
21.5 Writing data files
21.5.1 CSV and other delimited files
21.5.2 Writing Excel files
21.5.3 Packaging data files
Summary
22 Data over the network
22.1 Fetching files
22.1.1 Using Python to fetch files from an FTP server
22.1.2 Fetching files with SFTP
22.1.3 Retrieving files over HTTP/HTTPS
22.2 Fetching data via an API
22.3 Structured data formats
22.3.1 JSON data
22.3.2 XML data
22.4 Scraping web data
Summary
23 Saving data
23.1 Relational databases
23.1.1 The Python Database API
23.2 SQLite: Using the sqlite3 database
23.3 Using MySQL, PostgreSQL, and other relational databases
23.4 Making database handling easier with an ORM
23.4.1 SQLAlchemy
23.4.2 Using Alembic for database schema changes
23.5 NoSQL databases
23.6 key:value stores with Redis
23.7 Documents in MongoDB
Summary
24 Exploring data
24.1 Python tools for data exploration
24.1.1 Python?s advantages for exploring data
24.1.2 Python can be better than a spreadsheet
24.2 Jupyter notebook
24.2.1 Starting a kernel
24.2.2 Executing code in a cell
24.3 Python and pandas
24.3.1 Why you might want to use pandas
24.3.2 Installing pandas
24.3.3 Data frames
24.4 Data cleaning
24.4.1 Loading and saving data with pandas
24.4.2 Data cleaning with a data frame
24.5 Data aggregation and manipulation
24.5.1 Merging data frames
24.5.2 Selecting data
24.5.3 Grouping and aggregation
24.6 Plotting data
24.7 Why you might not want to use pandas
Summary
Case study
Downloading the data
Parsing the inventory data
Selecting a station based on latitude and longitude
Selecting a station and getting the station metadata
Fetching and parsing the actual weather data
Fetching the data
Parsing the weather data
Saving the weather data in a database (optional)
Selecting and graphing data
Using pandas to graph your data
appendix A
A guide to Python?s documentation
A.1 Accessing Python documentation on the web
A.1.1 Browsing Python documentation on your computer
A.1.2 Downloading documentation
A.2 Best practices: How to become a Pythonista
A.2.1 Ten tips for becoming a Pythonista
A.3 PEP 8?Style guide for Python code
A.3.1 Introduction
A.3.2 Code layout
A.4 Comments
A.4.1 Naming conventions
A.4.2 Programming recommendations
A.4.3 Other guides for Python style
A.5 The Zen of Python
appendix B
Exercise answers
B.1 Chapter 4
B.2 Chapter 5
B.3 Chapter 6
B.4 Chapter 7
B.5 Chapter 8
B.6 Chapter 9
B.7 Chapter 10
B.8 Chapter 11
B.9 Chapter 12
B.10 Chapter 13
B.11 Chapter 14
B.12 Chapter 15
B.13 Chapter 16
B.14 Chapter 17
B.15 Chapter 18
B.16 Chapter 20
B.17 Chapter 21
B.18 Chapter 22
B.19 Chapter 23
B.20 Chapter 24
index
Symbols
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
The Quick Python Book-back
Naomi Ceder Foreword by Nicholas Tollervey M A N N I N G
PRAISE FOR THE SECOND EDITION The quickest way to learn the basics of Python. —Massimo Perga, Microsoft This is my favorite Python book ... a competent way into serious Python programming. —Edmon Begoli, Oak Ridge National Laboratory Great book...covers the new incarnation of Python. —William Kahn-Greene, Participatory Culture Foundation Like Python itself, the book’s emphasis is on readability and rapid development. —David McWhirter, Cranberryink It’s definitely worth reading, and I would recommend that you buy it if you are new to Python. —Jerome Lanig, BayPiggies User Group Python coders will love this nifty book. —Sumit Pal, Leapfrogrx If you’ve ever wanted to learn Python or have a convenient desktop reference, this is the book for you. The author gives you a brief run-through of the language syntax and func- tional capabilities, then re-explores all aspects of the language as well as libraries and modules that extend Python into the space of practical applications. —Jim Kohli, Dzone This is the best book to learn Python for professional programmers or people who already know how to program in a different language … This won't be your only Python book, but it definitely has to be your first! —Amazon reader
The Quick Python Book
ii
The Quick Python Book THIRD EDITION NAOMI CEDER FOREWORD BY NICHOLAS TOLLERVEY M A N N I N G SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2018 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Development editor: Christina Taylor Technical development editor: Scott Steinman Project Manager: Janet Vail Copyeditor Kathy Simpson Proofreader: Elizabeth Martin Technical proofreader: André Brito Typesetter and cover design: Marija Tudor ISBN 9781617294037 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – EBM – 23 22 21 20 19 18
brief contents PART 1 STARTING OUT ............................................................ 1 1 ■ About Python 3 2 ■ Getting started 11 3 ■ The Quick Python overview 20 PART 2 THE ESSENTIALS ........................................................ 35 4 ■ The absolute basics 37 5 ■ Lists, tuples, and sets 49 6 ■ Strings 68 7 ■ Dictionaries 89 8 ■ Control flow 99 9 ■ Functions 113 10 ■ Modules and scoping rules 127 11 ■ Python programs 142 12 ■ Using the filesystem 158 13 ■ Reading and writing files 175 14 ■ Exceptions 190 PART 3 ADVANCED LANGUAGE FEATURES ............................. 205 15 ■ Classes and object-oriented programming 207 16 ■ Regular expressions 231 v
vi BRIEF CONTENTS 17 ■ Data types as objects 241 18 ■ Packages 255 19 ■ Using Python libraries 264 PART 4 WORKING WITH DATA .............................................. 273 20 ■ Basic file wrangling 275 21 ■ Processing data files 283 22 ■ Data over the network 300 23 ■ Saving data 319 24 ■ Exploring data 337 Case study 354
分享到:
收藏