logo资料库

python英文原版教程《Introducing_Python》.pdf

第1页 / 共476页
第2页 / 共476页
第3页 / 共476页
第4页 / 共476页
第5页 / 共476页
第6页 / 共476页
第7页 / 共476页
第8页 / 共476页
资料共476页,剩余部分请下载后查看
Cover
Copyright
Table of Contents
content
Preface
Audience
Outline
Python Versions
Conventions Used in This Book
Using Code Examples
Safari® Books Online
How to Contact Us
Acknowledgments
Chapter 1. A Taste of Py
Python in the Real World
Python versus Language X
So, Why Python?
When Not to Use Python
Python 2 versus Python 3
Installing Python
Running Python
Using the Interactive Interpreter
Use Python Files
What’s Next?
Your Moment of Zen
Things to Do
Chapter 2. Py Ingredients: Numbers, Strings, and Variables
Variables, Names, and Objects
Numbers
Integers
Precedence
Bases
Type Conversions
How Big Is an int?
Floats
Math Functions
Strings
Create with Quotes
Convert Data Types by Using str()
Escape with \
Combine with +
Duplicate with *
Extract a Character with []
Slice with [ start : end : step ]
Get Length with len()
Split with split()
Combine with join()
Playing with Strings
Case and Alignment
Substitute with replace()
More String Things
Things to Do
Chapter 3. Py Filling: Lists, Tuples, Dictionaries, and Sets
Lists and Tuples
Lists
Create with [] or list()
Convert Other Data Types to Lists with list()
Get an Item by Using [ offset ]
Lists of Lists
Change an Item by [ offset ]
Get a Slice to Extract Items by Offset Range
Add an Item to the End with append()
Combine Lists by Using extend() or +=
Add an Item by Offset with insert()
Delete an Item by Offset with del
Delete an Item by Value with remove()
Get an Item by Offset and Delete It by Using pop()
Find an Item’s Offset by Value with index()
Test for a Value with in
Count Occurrences of a Value by Using count()
Convert to a String with join()
Reorder Items with sort()
Get Length by Using len()
Assign with =, Copy with copy()
Tuples
Create a Tuple by Using ()
Tuples versus Lists
Dictionaries
Create with {}
Convert by Using dict()
Add or Change an Item by [ key ]
Combine Dictionaries with update()
Delete an Item by Key with del
Delete All Items by Using clear()
Test for a Key by Using in
Get an Item by [ key ]
Get All Keys by Using keys()
Get All Values by Using values()
Get All Key-Value Pairs by Using items()
Assign with =, Copy with copy()
Sets
Create with set()
Convert from Other Data Types with set()
Test for Value by Using in
Combinations and Operators
Compare Data Structures
Make Bigger Data Structures
Things to Do
Chapter 4. Py Crust: Code Structures
Comment with #
Continue Lines with \
Compare with if, elif, and else
What Is True?
Repeat with while
Cancel with break
Skip Ahead with continue
Check break Use with else
Iterate with for
Cancel with break
Skip with continue
Check break Use with else
Iterate Multiple Sequences with zip()
Generate Number Sequences with range()
Other Iterators
Comprehensions
List Comprehensions
Dictionary Comprehensions
Set Comprehensions
Generator Comprehensions
Functions
Positional Arguments
Keyword Arguments
Specify Default Parameter Values
Gather Positional Arguments with *
Gather Keyword Arguments with **
Docstrings
Functions Are First-Class Citizens
Inner Functions
Closures
Anonymous Functions: the lambda() Function
Generators
Decorators
Namespaces and Scope
Uses of _ and __ in Names
Handle Errors with try and except
Make Your Own Exceptions
Things to Do
Chapter 5. Py Boxes: Modules, Packages, and Programs
Standalone Programs
Command-Line Arguments
Modules and the import Statement
Import a Module
Import a Module with Another Name
Import Only What You Want from a Module
Module Search Path
Packages
The Python Standard Library
Handle Missing Keys with setdefault() and defaultdict()
Count Items with Counter()
Order by Key with OrderedDict()
Stack + Queue == deque
Iterate over Code Structures with itertools
Print Nicely with pprint()
More Batteries: Get Other Python Code
Things to Do
Chapter 6. Oh Oh: Objects and Classes
What Are Objects?
Define a Class with class
Inheritance
Override a Method
Add a Method
Get Help from Your Parent with super
In self Defense
Get and Set Attribute Values with Properties
Name Mangling for Privacy
Method Types
Duck Typing
Special Methods
Composition
When to Use Classes and Objects versus Modules
Named Tuples
Things to Do
Chapter 7. Mangle Data Like a Pro
Text Strings
Unicode
Format
Match with Regular Expressions
Binary Data
bytes and bytearray
Convert Binary Data with struct
Other Binary Data Tools
Convert Bytes/Strings with binascii()
Bit Operators
Things to Do
Chapter 8. Data Has to Go Somewhere
File Input/Output
Write a Text File with write()
Read a Text File with read(), readline(), or readlines()
Write a Binary File with write()
Read a Binary File with read()
Close Files Automatically by Using with
Change Position with seek()
Structured Text Files
CSV
XML
HTML
JSON
YAML
A Security Note
Configuration Files
Other Interchange Formats
Serialize by Using pickle
Structured Binary Files
Spreadsheets
HDF5
Relational Databases
SQL
DB-API
SQLite
MySQL
PostgreSQL
SQLAlchemy
NoSQL Data Stores
The dbm Family
Memcached
Redis
Other NoSQL
Full-Text Databases
Things to Do
Chapter 9. The Web, Untangled
Web Clients
Test with telnet
Python’s Standard Web Libraries
Beyond the Standard Library: Requests
Web Servers
The Simplest Python Web Server
Web Server Gateway Interface
Frameworks
Bottle
Flask
Non-Python Web Servers
Other Frameworks
Web Services and Automation
The webbrowser Module
Web APIs and Representational State Transfer
JSON
Crawl and Scrape
Scrape HTML with BeautifulSoup
Things to Do
Chapter 10. Systems
Files
Create with open()
Check Existence with exists()
Check Type with isfile()
Copy with copy()
Change Name with rename()
Link with link() or symlink()
Change Permissions with chmod()
Change Ownership with chown()
Get a Pathname with abspath()
Get a symlink Pathname with realpath()
Delete a File with remove()
Directories
Create with mkdir()
Delete with rmdir()
List Contents with listdir()
Change Current Directory with chdir()
List Matching Files with glob()
Programs and Processes
Create a Process with subprocess
Create a Process with multiprocessing
Kill a Process with terminate()
Calendars and Clocks
The datetime Module
Using the time Module
Read and Write Dates and Times
Alternative Modules
Things to Do
Chapter 11. Concurrency and Networks
Concurrency
Queues
Processes
Threads
Green Threads and gevent
twisted
asyncio
Redis
Beyond Queues
Networks
Patterns
The Publish-Subscribe Model
TCP/IP
Sockets
ZeroMQ
Scapy
Internet Services
Web Services and APIs
Remote Processing
Big Fat Data and MapReduce
Working in the Clouds
Things to Do
Chapter 12. Be a Pythonista
About Programming
Find Python Code
Install Packages
Use pip
Use a Package Manager
Install from Source
Integrated Development Environments
IDLE
PyCharm
IPython
Name and Document
Testing Your Code
Check with pylint, pyflakes, and pep8
Test with unittest
Test with doctest
Test with nose
Other Test Frameworks
Continuous Integration
Debugging Python Code
Debug with pdb
Logging Error Messages
Optimize Your Code
Measure Timing
Algorithms and Data Structures
Cython, NumPy, and C Extensions
PyPy
Source Control
Mercurial
Git
Clone This Book
How You Can Learn More
Books
Websites
Groups
Conferences
Coming Attractions
Appendix A. Py Art
2-D Graphics
Standard Library
PIL and Pillow
ImageMagick
Graphical User Interfaces (GUIs)
3-D Graphics and Animation
Plots, Graphs, and Visualization
matplotlib
bokeh
Games
Audio and Music
>>>prompt
Appendix B. Py at Work
The Microsoft Office Suite
Carrying Out Business Tasks
Processing Business Data
Extracting, Transforming, and Loading
Additional Sources of Information
Python in Finance
Business Data Security
Maps
Formats
Draw a Map
Applications and Data
Appendix C. Py Sci
Math and Statistics in the Standard Library
Math Functions
Working with Complex Numbers
Calculate Accurate Floating Point with decimal
Perform Rational Arithmetic with fractions
Use Packed Sequences with array
Handling Simple Stats by Using statistics
Matrix Multiplication
Scientific Python
NumPy
Make an Array with array()
Make an Array with arange()
Make an Array with zeros(), ones(), or random()
Change an Array’s Shape with reshape()
Get an Element with []
Array Math
Linear Algebra
The SciPy Library
The SciKit Library
The IPython Library
A Better Interpreter
IPython Notebook
Pandas
Python and Scientific Areas
Appendix D. Install Python 3
Install Standard Python
Mac OS X
Windows
Linux or Unix
Install Anaconda
Install and Use pip and virtualenv
Install and Use conda
Appendix E. Answers to Exercises
Chapter 1, A Taste of Py
Chapter 2, Py Ingredients: Numbers, Strings, and Variables
Chapter 3, Py Filling: Lists, Tuples, Dictionaries, and Sets
Chapter 4, Py Crust: Code Structures
Chapter 5, Py Boxes: Modules, Packages, and Programs
Chapter 6, Oh Oh: Objects and Classes
Chapter 7, Mangle Data Like a Pro
Chapter 8, Data Has to Go Somewhere
Chapter 9, The Web, Untangled
Chapter 10, Systems
Chapter 11, Concurrency and Networks
Appendix F. Cheat Sheets
Operator Precedence
String Methods
Change Case
Search
Modify
Format
String Type
String Module Attributes
Fin
Index
About the Author
Introducing Python Bill Lubanovic
Introducing Python by Bill Lubanovic Copyright © 2015 Bill Lubanovic. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com. Editors: Andy Oram and Allyson MacDonald Production Editor: Nicole Shelby Copyeditor: Octal Publishing Proofreader: Sonia Saruba Indexer: Judy McConville Cover Designer: Ellie Volckhausen Interior Designer: David Futato Illustrator: Rebecca Demarest November 2014: First Edition Revision History for the First Edition: 2014-11-07: First release 2015-02-20: Second release See http://oreilly.com/catalog/errata.csp?isbn=9781449359362 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Introducing Python, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. 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 O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While the publisher and the author have used good faith efforts to ensure that the information and instruc‐ tions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intel‐ lectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. ISBN: 978-1-449-35936-2 [LSI]
To Mary, Karin, Tom, and Roxie.
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv 1. A Taste of Py. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Python in the Real World 5 Python versus Language X 6 So, Why Python? 9 When Not to Use Python 9 Python 2 versus Python 3 10 Installing Python 10 Running Python 11 Using the Interactive Interpreter 11 Use Python Files 12 What’s Next? 13 Your Moment of Zen 13 Things to Do 14 2. Py Ingredients: Numbers, Strings, and Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Variables, Names, and Objects 15 Numbers 19 Integers 19 Precedence 23 Bases 24 Type Conversions 25 How Big Is an int? 26 Floats 27 Math Functions 27 Strings 27 Create with Quotes 28 Convert Data Types by Using str() 30 v
Escape with \ 30 Combine with + 31 Duplicate with * 32 Extract a Character with [] 32 Slice with [ start : end : step ] 33 Get Length with len() 35 Split with split() 35 Combine with join() 36 Playing with Strings 36 Case and Alignment 37 Substitute with replace() 38 More String Things 39 Things to Do 39 3. Py Filling: Lists, Tuples, Dictionaries, and Sets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Lists and Tuples 41 Lists 42 Create with [] or list() 42 Convert Other Data Types to Lists with list() 43 Get an Item by Using [ offset ] 43 Lists of Lists 44 Change an Item by [ offset ] 45 Get a Slice to Extract Items by Offset Range 45 Add an Item to the End with append() 46 Combine Lists by Using extend() or += 46 Add an Item by Offset with insert() 46 Delete an Item by Offset with del 47 Delete an Item by Value with remove() 47 Get an Item by Offset and Delete It by Using pop() 47 Find an Item’s Offset by Value with index() 48 Test for a Value with in 48 Count Occurrences of a Value by Using count() 49 Convert to a String with join() 49 Reorder Items with sort() 49 Get Length by Using len() 50 Assign with =, Copy with copy() 50 Tuples 52 Create a Tuple by Using () 52 Tuples versus Lists 53 Dictionaries 53 Create with {} 54 Convert by Using dict() 54 vi | Table of Contents
分享到:
收藏