Statistics
6
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-12

AuthorNaomi Ceder

No description

Tags
No tags
ISBN: 1617294039
Publisher: Manning Publications
Publish Year: 2018
Language: 英文
Pages: 533
File Format: PDF
File Size: 13.8 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Copyright 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.     PO Box 761       History Topics Tutorials Offers & Deals Highlights Settings Support Sign Out 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 Table of Contents Copyright Brief Table of Contents Table of Contents Praise for the second edition Foreword Preface Acknowledgments About this book About the cover illustration 1. Starting out Chapter 1. About Python Chapter 2. Getting started Chapter 3. The Quick Python overview 2. The essentials Chapter 4. The absolute basics Chapter 5. Lists, tuples, and sets Chapter 6. Strings Chapter 7. Dictionaries Playlists History Topics Tutorials Offers & Deals Highlights Settings Support Sign Out
Chapter 8. Control flow Chapter 9. Functions Chapter 10. Modules and scoping rules Chapter 11. Python programs Chapter 12. Using the filesystem Chapter 13. Reading and writing files Chapter 14. Exceptions 3. Advanced language features Chapter 15. Classes and object­oriented programming Chapter 16. Regular expressions Chapter 17. Data types as objects Chapter 18. Packages Chapter 19. Using Python libraries 4. Working with data Chapter 20. Basic file wrangling Chapter 21. Processing data files Chapter 22. Data over the network Chapter 23. Saving data Chapter 24. Exploring data  Case study A. A guide to Python’s documentation B. Exercise answers
Index List of Figures List of Tables List of Listings
Part 1. Starting out These first three chapters tell you a little bit about Python, its strengths and weaknesses, and why you should consider learning Python 3. In chapter 2 you see how to install Python on Windows, macOS, and Linux platforms and how to write a simple program. Chapter 3 is a quick, high­level survey of Python’s syntax and features. If you’re looking for the quickest possible introduction to Python, start with chapter 3. Playlists History Topics Tutorials Offers & Deals Highlights Settings Support Sign Out
Chapter 1. About Python This chapter covers Why use Python? What Python does well What Python doesn’t do as well Why learn Python 3? Read this chapter if you want to know how Python compares to other languages and its place in the grand scheme of things. Skip ahead—go straight to chapter 3—if you want to start learning Python right away. The information in this chapter is a valid part of this book—but it’s certainly not necessary for programming with Python. 1.1. WHY SHOULD I USE PYTHON? Hundreds of programming languages are available today, from mature languages like C and C++, to newer entries like Ruby, C#, and Lua, to enterprise juggernauts like Java. Choosing a language to learn is difficult. Although no one language is the right choice for every possible situation, I think that Python is a good choice for a large number of programming problems, and it’s also a good choice if you’re learning to program. Hundreds of thousands of programmers around the world use Python, and the number grows every year. Python continues to attract new users for a variety of reasons. It’s a true cross­platform language, running equally well on Windows, Linux/UNIX, and Macintosh platforms, as well as others, ranging from supercomputers to cell phones. It can be used to develop small applications and rapid prototypes, but it scales well to permit development of large programs. It comes with a powerful and easy­to­use graphical user interface (GUI) toolkit, web programming libraries, and more. And it’s free. 1.2. WHAT PYTHON DOES WELL Python is a modern programming language developed by Guido van Rossum in the Playlists History Topics Tutorials Offers & Deals Highlights Settings Support Sign Out
1990s (and named after a famous comedic troupe). Although Python isn’t perfect for every application, its strengths make it a good choice for many situations. 1.2.1. Python is easy to use Programmers familiar with traditional languages will find it easy to learn Python. All of the familiar constructs—loops, conditional statements, arrays, and so forth—are included, but many are easier to use in Python. Here are a few of the reasons why: Types are associated with objects, not variables. A variable can be assigned a value of any type, and a list can contain objects of many types. This also means that type casting usually isn’t necessary and that your code isn’t locked into the straitjacket of predeclared types. Python typically operates at a much higher level of abstraction. This is partly the result of the way the language is built and partly the result of an extensive standard code library that comes with the Python distribution. A program to download a web page can be written in two or three lines! Syntax rules are very simple. Although becoming an expert Pythonista takes time and effort, even beginners can absorb enough Python syntax to write useful code quickly. Python is well suited for rapid application development. It isn’t unusual for coding an application in Python to take one­fifth the time it would in C or Java and to take as little as one­fifth the number of lines of the equivalent C program. This depends on the particular application, of course; for a numerical algorithm performing mostly integer arithmetic in for loops, there would be much less of a productivity gain. For the average application, the productivity gain can be significant. 1.2.2. Python is expressive Python is a very expressive language. Expressive in this context means that a single line of Python code can do more than a single line of code in most other languages. The advantages of a more expressive language are obvious: The fewer lines of code you have to write, the faster you can complete the project. The fewer lines of code there are, the easier the program will be to maintain and debug. To get an idea of how Python’s expressiveness can simplify code, consider swapping the values of two variables, var1 and var2. In a language like Java, this requires three lines of code and an extra variable:
int temp = var1; var1 = var2; var2 = temp; The variable temp is needed to save the value of var1 when var2 is put into it, and then that saved value is put into var2. The process isn’t terribly complex, but reading those three lines and understanding that a swap has taken place takes a certain amount of overhead, even for experienced coders. By contrast, Python lets you make the same swap in one line and in a way that makes it obvious that a swap of values has occurred: var2, var1 = var1, var2 Of course, this is a very simple example, but you find the same advantages throughout the language. 1.2.3. Python is readable Another advantage of Python is that it’s easy to read. You might think that a programming language needs to be read only by a computer, but humans have to read your code as well: whoever debugs your code (quite possibly you), whoever maintains your code (could be you again), and whoever might want to modify your code in the future. In all of those situations, the easier the code is to read and understand, the better it is. The easier code is to understand, the easier it is to debug, maintain, and modify. Python’s main advantage in this department is its use of indentation. Unlike most languages, Python insists that blocks of code be indented. Although this strikes some people as odd, it has the benefit that your code is always formatted in a very easy­to­ read style. Following are two short programs, one written in Perl and one in Python. Both take two equal­size lists of numbers and return the pairwise sum of those lists. I think the Python code is more readable than the Perl code; it’s visually cleaner and contains fewer inscrutable symbols: # Perl version. sub pairwise_sum {     my($arg1, $arg2) = @_;     my @result;
    for(0 .. $#$arg1) {         push(@result, $arg1­>[$_] + $arg2­>[$_]);     }     return(\@result); } # Python version. def pairwise_sum(list1, list2):     result = []     for i in range(len(list1)):         result.append(list1[i] + list2[i])     return result Both pieces of code do the same thing, but the Python code wins in terms of readability. (There are other ways to do this in Perl, of course, some of which are much more concise—but in my opinion harder to read—than the one shown.) 1.2.4. Python is complete—“batteries included” Another advantage of Python is its “batteries included” philosophy when it comes to libraries. The idea is that when you install Python, you should have everything you need to do real work without the need to install additional libraries. This is why the Python standard library comes with modules for handling email, web pages, databases, operating­system calls, GUI development, and more. For example, with Python, you can write a web server to share the files in a directory with just two lines of code: import http.server http.server.test(HandlerClass=http.server.SimpleHTTPRequestHandler) There’s no need to install libraries to handle network connections and HTTP; it’s already in Python, right out of the box. 1.2.5. Python is cross-platform Python is also an excellent cross­platform language. Python runs on many platforms: Windows, Mac, Linux, UNIX, and so on. Because it’s interpreted, the same code can run on any platform that has a Python interpreter, and almost all current platforms have one. There are even versions of Python that run on Java (Jython) and .NET (IronPython), giving you even more possible platforms that run Python 1.2.6. Python is free
Python is also free. Python was originally, and continues to be, developed under the open source model, and it’s freely available. You can download and install practically any version of Python and use it to develop software for commercial or personal applications, and you don’t need to pay a dime. Although attitudes are changing, some people are still leery of free software because of concerns about a lack of support, fearing that they lack the clout of paying customers. But Python is used by many established companies as a key part of their business; Google, Rackspace, Industrial Light & Magic, and Honeywell are just a few examples. These companies and many others know Python for what it is: a very stable, reliable, and well­supported product with an active and knowledgeable user community. You’ll get an answer to even the most difficult Python question more quickly on the Python internet newsgroup than you will on most tech­support phone lines, and the Python answer will be free and correct. Python and open source software Not only is Python free of cost, but also, its source code is freely available, and you’re free to modify, improve, and extend it if you want. Because the source code is freely available, you have the ability to go in yourself and change it (or to hire someone to go in and do so for you). You rarely have this option at any reasonable cost with proprietary software. If this is your first foray into the world of open source software, you should understand that you’re not only free to use and modify Python, but also able (and encouraged) to contribute to it and improve it. Depending on your circumstances, interests, and skills, those contributions might be financial, as in a donation to the Python Software Foundation (PSF), or they may involve participating in one of the special interest groups (SIGs), testing and giving feedback on releases of the Python core or one of the auxiliary modules, or contributing some of what you or your company develops back to the community. The level of contribution (if any) is, of course, up to you; but if you’re able to give back, definitely consider doing so. Something of significant value is being created here, and you have an opportunity to add to it. Python has a lot going for it: expressiveness, readability, rich included libraries, and cross­platform capabilities. Also, it’s open source. What’s the catch? 1.3. WHAT PYTHON DOESN’T DO AS WELL
Although Python has many advantages, no language can do everything, so Python isn’t the perfect solution for all your needs. To decide whether Python is the right language for your situation, you also need to consider the areas where Python doesn’t do as well. 1.3.1. Python isn’t the fastest language A possible drawback with Python is its speed of execution. It isn’t a fully compiled language. Instead, it’s first compiled to an internal bytecode form, which is then executed by a Python interpreter. There are some tasks, such as string parsing using regular expressions, for which Python has efficient implementations and is as fast as, or faster than, any C program you’re likely to write. Nevertheless, most of the time, using Python results in slower programs than in a language like C. But you should keep this in perspective. Modern computers have so much computing power that for the vast majority of applications, the speed of the program isn’t as important as the speed of development, and Python programs can typically be written much more quickly. In addition, it’s easy to extend Python with modules written in C or C++, which can be used to run the CPU­intensive portions of a program. 1.3.2. Python doesn’t have the most libraries Although Python comes with an excellent collection of libraries, and many more are available, Python doesn’t hold the lead in this department. Languages like C, Java, and Perl have even larger collections of libraries available, in some cases offering a solution where Python has none or a choice of several options where Python might have only one. These situations tend to be fairly specialized, however, and Python is easy to extend, either in Python itself or through existing libraries in C and other languages. For almost all common computing problems, Python’s library support is excellent. 1.3.3. Python doesn’t check variable types at compile time Unlike in some languages, Python’s variables don’t work like containers; instead, they’re more like labels that reference various objects: integers, strings, class instances, whatever. That means that although those objects themselves have types, the variables referring to them aren’t bound to that particular type. It’s possible (if not necessarily desirable) to use the variable x to refer to a string in one line and an integer in another: >>> x = "2" >>> x '2'                    1 >>> x = int(x) >>> x 2                      2
1 x is string “2” 2 x is now integer 2 The fact that Python associates types with objects and not with variables means that the interpreter doesn’t help you catch variable type mismatches. If you intend a variable count to hold an integer, Python won’t complain if you assign the string "two" to it. Traditional coders count this as a disadvantage, because you lose an additional free check on your code. But errors like this usually aren’t hard to find and fix, and Python’s testing features makes avoiding type errors manageable. Most Python programmers feel that the flexibility of dynamic typing more than outweighs the cost. 1.3.4. Python doesn’t have much mobile support In the past decade the numbers and types of mobile devices have exploded, and smartphones, tablets, phablets, Chromebooks, and more are everywhere, running on a variety of operating systems. Python isn’t a strong player in this space. While options exist, running Python on mobile devices isn’t always easy, and using Python to write and distribute commercial apps is problematic. 1.3.5. Python doesn’t use multiple processors well Multiple­core processors are everywhere now, producing significant increases in performance in many situations. However, the standard implementation of Python isn’t designed to use multiple cores, due to a feature called the global interpreter lock (GIL). For more information, look for videos of GIL­related talks and posts by David Beazley, Larry Hastings, and others, or visit the GIL page on the Python wiki at https://wiki.python.org/moin/GlobalInterpreterLock. While there are ways to run concurrent processes by using Python, if you need concurrency out of the box, Python may not be for you. 1.4. WHY LEARN PYTHON 3? Python has been around for a number of years and has evolved over that time. The first edition of this book was based on Python 1.5.2, and Python 2.x has been the dominant version for several years. This book is based on Python 3.6 but has also been tested on the alpha version of Python 3.7. Python 3, originally whimsically dubbed Python 3000, is notable because it’s the first version of Python in the history of the language to break backward compatibility. What this means is that code written for earlier versions of Python probably won’t run on Python 3 without some changes. In earlier versions of Python, for example, the print
statement didn’t require parentheses around its arguments: print "hello" In Python 3, print is a function and needs the parentheses: print("hello") You may be thinking, “Why change details like this if it’s going to break old code?” Because this kind of change is a big step for any language, the core developers of Python thought about this issue carefully. Although the changes in Python 3 break compatibility with older code, those changes are fairly small and for the better; they make the language more consistent, more readable, and less ambiguous. Python 3 isn’t a dramatic rewrite of the language; it’s a well­thought­out evolution. The core developers also took care to provide a strategy and tools to safely and efficiently migrate old code to Python 3, which will be discussed in a later chapter, and the Six and Future libraries are also available to make the transition easier. Why learn Python 3? Because it’s the best Python so far. Also, as projects switch to take advantage of its improvements, it will be the dominant Python version for years to come. The porting of libraries to Python 3 has been steady since its introduction, and by now many of the most popular libraries support Python 3. In fact, according to the Python Readiness page (http://py3readiness.org), 319 of the 360 most popular libraries have already been ported to Python 3. If you need a library that hasn’t been converted yet, or if you’re working on an established code base in Python 2, by all means stick with Python 2.x. But if you’re starting to learn Python or starting a project, go with Python 3; it’s not only better, but also the future. SUMMARY Python is a modern, high­level language with dynamic typing and simple, consistent syntax and semantics. Python is multiplatform, highly modular, and suited for both rapid development and large­scale programming. It’s reasonably fast and can be easily extended with C or C++ modules for higher speeds. Python has built­in advanced features such as persistent object storage, advanced hash tables, expandable class syntax, and universal comparison functions.
Python includes a wide range of libraries such as numeric processing, image manipulation, user interfaces, and web scripting. It’s supported by a dynamic Python community.
Chapter 2. Getting started This chapter covers Installing Python Using IDLE and the basic interactive mode Writing a simple program Using IDLE’s Python shell window This chapter guides you through downloading, installing, and starting up Python and IDLE, an integrated development environment for Python. At this writing, Python 3.6 is the most current version, and 3.7 is under development. After years of refinement, Python 3 is the first version of the language that isn’t fully backward­compatible with earlier versions, so be sure to get a version of Python 3. It should be several years before another such dramatic change occurs, and any future enhancements will be developed with concern to avoid affecting an already­significant existing code base. Therefore, the material presented after this chapter isn’t likely to become dated any time soon. 2.1. INSTALLING PYTHON Installing Python is a simple matter, regardless of which platform you’re using. The first step is to obtain a recent distribution for your machine; the most recent one can always be found at www.python.org. This book is based on Python 3.6. If you have Python 3.5 or even 3.7, that’s fine. In fact, you should have little trouble using most of this book with any version of Python 3. Having more than one version of Python You may already have an earlier version of Python installed on your machine. Many Linux distributions and macOS come with Python 2.x as part of the operating system. Because Python 3 isn’t completely compatible with Python 2, it’s reasonable to wonder whether installing both versions on the same computer will cause a conflict. History Topics Tutorials Offers & Deals Highlights Settings Support Sign Out
There’s no need to worry; you can have multiple versions of Python on the same computer. In the case of UNIX­based systems like OS X and Linux, Python 3 installs alongside the older version and doesn’t replace it. When your system looks for “python,” it still finds the one it expects, and when you want to access Python 3, you can run python3 or idle. In Windows, the different versions are installed in separate locations and have separate menu entries. Some basic platform­specific descriptions for the Python installation are given next. The specifics can vary quite a bit depending on your platform, so be sure to read the instructions on the download pages and for the various versions. You’re probably familiar with installing software on your particular machine, so I’ll keep these descriptions short: Microsoft Windows— Python can be installed in most versions of Windows by using the Python installer program, currently called python­3.6.1.exe. Download it, execute it, and follow the installer’s prompts. You may need to be logged in as administrator to run the install. If you’re on a network and don’t have the administrator password, ask your system administrator to do the installation for you. Macintosh— You need to get a version of Python 3 that matches your OS X version and your processor. After you determine the correct version, download the disk image file, double­click to mount it, and run the installer inside. The OS X installer sets up everything automatically, and Python 3 will be in a subfolder inside the Applications folder, labeled with the version number. macOS ships with various versions of Python as part of the system, but you don’t need to worry about that; Python 3 will be installed in addition to the system version. If you have brew installed, you can also use it to install Python by using the command brew install python3. You can find more information about using Python on OS X by following the links on the Python home page. Linux/UNIX— Most Linux distributions come with Python installed. But the versions of Python vary, and the version of Python installed may not be version 3; for this book, you need to be sure you have the Python 3 packages installed. It’s also possible that IDLE isn’t installed by default and that you’ll need to install that package separately. Although it’s also possible to build Python 3 from the source code available on the www.python.org website, additional libraries are needed, and the process isn’t for novices. If a precompiled version of Python exists for your distribution of Linux, I recommend using that. Use the software management
system for your distribution to locate and install the correct packages for Python 3 and IDLE. Versions are also available for running Python under many other operating systems. See www.python.org for a current list of supported platforms and specifics on installation. Anaconda: an alternative Python distribution In addition to the distribution of Python that you can get directly from Python.org, a distribution called Anaconda is gaining popularity, particularly among scientific and data science users. Anaconda is an open data science platform with Python at its core. When you install Anaconda, you get not only Python, but also the R language and a generous collection of preinstalled data science packages, and you can add many more by using the included conda package manager. You can also install miniconda, which includes only Python and conda, and then add the packages you need. You can get Anaconda or miniconda from www.anaconda.com/download/. Download the Python 3 version of the installer that matches your operating system, and run it according to the instructions. When that’s done, you’ll have a full version of Python on your machine. Particularly if your primary interest is in data science, you may find Anaconda to be a quicker and easier way to get up and running with Python. 2.2. BASIC INTERACTIVE MODE AND IDLE You have two built­in options for obtaining interactive access to the Python interpreter: the original basic (command­line) mode and IDLE. IDLE is available on many platforms, including Windows, Mac, and Linux, but it may not be available on others. You may need to do more work and install additional software packages to get IDLE running, but doing so will be worthwhile because IDLE offers a somewhat smoother experience than the basic interactive mode. On the other hand, even if you normally use IDLE, at times you’ll likely want to fire up the basic mode. You should be familiar enough to start and use either one. 2.2.1. The basic interactive mode The basic interactive mode is a rather primitive environment, but the interactive examples in this book are generally small. Later in this book, you learn how to easily bring code you’ve placed in a file into your session (by using the module mechanism).
Here’s how to start a basic session on Windows, macOS, and UNIX: Starting a basic session on Windows— For version 3.x of Python, you navigate to the Python 3.6 (32­bit) entry on the Python 3.6 submenu of the Programs folder on the Start menu, and click it. Alternatively, you can directly find the Python.exe executable (for example, in C:\Users\myuser\AppData\Local\Programs\Python \Python35­32) and double­ click it. Doing so brings up the window shown in figure 2.1. Figure 2.1. Basic interactive mode on Windows 10 Starting a basic session on macOS— Open a terminal window and type python3. If you get a “Command not found” error, run the Update Shell Profile command script located in the Python3 subfolder in the Applications folder. Starting a basic session on UNIX— Type python3 at a command prompt. A version message similar to the one shown in figure 2.1 followed by the Python prompt >>> appears in the current window. Exiting the interactive shell To exit from a basic session, press Ctrl­Z (if you’re on Windows) or Ctrl­D (if you’re on Linux or UNIX), or type exit() at a command prompt. Most platforms have a command­line­editing and command­history mechanism. You can use the up and down arrows, as well as the Home, End, Page Up, and Page Down keys, to scroll through past entries and repeat them by pressing the Enter key. This is all you need to work your way through this book as you’re learning Python. Another option is to use the excellent Python mode available for Emacs, which, among other things, provides access to the interactive mode of Python through an integrated shell buffer. 2.2.2. The IDLE integrated development environment