Python For Everybody - Charles Severance

Transcription

Python for EverybodyExploring Data Using PythonCharles R. Severance

CreditsEditorial Support: Elliott Hauser, Sue BlumenbergCover Design: Aimee AndrionPrinting History -Jul- First Complete Python . version-Dec- Initial Python . rough conversionCopyright DetailsCopyright - Charles Severance.This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike. Unported License. This license is available athttp://creativecommons.org/licenses/by-nc-sa/ . /You can see what the author considers commercial and non-commercial uses of this material as well as license exemptions in the Appendix titled “Copyright Detail”.

iiiPrefaceRemixing an Open BookIt is quite natural for academics who are continuously told to “publish or perish” towant to always create something from scratch that is their own fresh creation. This bookis an experiment in not starting from scratch, but instead “remixing” the book titledThink Python: How to Think Like a Computer Scientist written by Allen B. Downey, JeffElkner, and others.In December of, I was preparing to teach SI- Networked Programming at theUniversity of Michigan for the fifth semester in a row and decided it was time to writea Python textbook that focused on exploring data instead of understanding algorithmsand abstractions. My goal in SIis to teach people lifelong data handling skills usingPython. Few of my students were planning to be professional computer programmers.Instead, they planned to be librarians, managers, lawyers, biologists, economists, etc.,who happened to want to skillfully use technology in their chosen field.I never seemed to find the perfect data-oriented Python book for my course, so I set outto write just such a book. Luckily at a faculty meeting three weeks before I was about tostart my new book from scratch over the holiday break, Dr. Atul Prakash showed me theThink Python book which he had used to teach his Python course that semester. It is awell-written Computer Science text with a focus on short, direct explanations and ease oflearning.The overall book structure has been changed to get to doing data analysis problems asquickly as possible and have a series of running examples and exercises about data analysis from the very beginning.Chapters ‒ are similar to the Think Python book, but there have been major changes.Number-oriented examples and exercises have been replaced with data-oriented exercises. Topics are presented in the order needed to build increasingly sophisticated dataanalysis solutions. Some topics like try and except are pulled forward and presentedas part of the chapter on conditionals. Functions are given very light treatment until theyare needed to handle program complexity rather than introduced as an early lesson in abstraction. Nearly all user-defined functions have been removed from the example codeand exercises outside of Chapter . The word “recursion” does not appear in the bookat all.In chapters and ‒ , all of the material is brand new, focusing on real-world usesand simple examples of Python for data analysis including regular expressions for searching and parsing, automating tasks on your computer, retrieving data across the network,scraping web pages for data, object-oriented programming, using web services, parsingXML and JSON data, creating and using databases using Structured Query Language, andvisualizing data.The ultimate goal of all of these changes is a shift from a Computer Science to an Informatics focus is to only include topics into a first technology class that can be useful evenif one chooses not to become a professional programmer.Students who find this book interesting and want to further explore should look at Allen B.Downey’s Think Python book. Because there is a lot of overlap between the two books,Except, of course, for this line.

ivstudents will quickly pick up skills in the additional areas of technical programming andalgorithmic thinking that are covered in Think Python. And given that the books have asimilar writing style, they should be able to move quickly through Think Python with aminimum of effort.As the copyright holder of Think Python, Allen has given me permission to change thebook’s license on the material from his book that remains in this book from the GNUFree Documentation License to the more recent Creative Commons Attribution — ShareAlike license. This follows a general shift in open documentation licenses moving fromthe GFDL to the CC-BY-SA (e.g., Wikipedia). Using the CC-BY-SA license maintains thebook’s strong copyleft tradition while making it even more straightforward for new authors to reuse this material as they see fit.I feel that this book serves an example of why open materials are so important to thefuture of education, and want to thank Allen B. Downey and Cambridge University Pressfor their forward-looking decision to make the book available under an open copyright.I hope they are pleased with the results of my efforts and I hope that you the reader arepleased with our collective efforts.I would like to thank Allen B. Downey and Lauren Cowles for their help, patience, andguidance in dealing with and resolving the copyright issues around this book.Charles Severancewww.dr-chuck.comAnn Arbor, MI, USASeptember ,Charles Severance is a Clinical Associate Professor at the University of Michigan Schoolof Information.

Contents为什么要学编程?.创新与动机 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .计算机硬件架构 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .理解编程 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .词汇与句 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .与Python对话.术语:解释器与编译器 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .编写 个程序 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .什么是程序? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .构成程序的小积木 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .什么可能会出错? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .学习之旅 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .术语表 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .习题 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .变量、表达式、语句.值与类型 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .变量 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .变量名与关键字 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .语句 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .运算符和运算对象 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .表达式 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .运算顺序 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .模运算 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .字符串运算符 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .请求 输 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .v

viCONTENTS.注释 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .助记变量命名法 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .调试 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .术语表 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .习题 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .条件执 .布尔表达式 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .逻辑运算符 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Conditional execution . . . . . . . . . . . . . . . . . . . . . . . . . . . .Alternative execution . . . . . . . . . . . . . . . . . . . . . . . . . . . .Chained conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . .Nested conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Catching exceptions using try and except . . . . . . . . . . . . . . . . . .Short-circuit evaluation of logical expressions.Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Functions.Function calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Type conversion functions . . . . . . . . . . . . . . . . . . . . . . . . . .Random numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Math functions.Adding new functions . . . . . . . . . . . . . . . . . . . . . . . . . . . .Definitions and uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Flow of execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Parameters and arguments . . . . . . . . . . . . . . . . . . . . . . . . .Fruitful functions and void functions . . . . . . . . . . . . . . . . . . . .Why functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

CONTENTSviiIteration.Updating variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The while statement . . . . . . . . . . . . . . . . . . . . . . . . . . . .Infinite loops.“Infinite loops” and break . . . . . . . . . . . . . . . . . . . . . . . .Finishing iterations with continue . . . . . . . . . . . . . . . . . . . . .Definite loops using for . . . . . . . . . . . . . . . . . . . . . . . . . . .Loop patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Counting and summing loops. . . . . . . . . . . . . . . . . . . . .Maximum and minimum loops . . . . . . . . . . . . . . . . . . . .Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Strings.A string is a sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . .Getting the length of a string using len . . . . . . . . . . . . . . . . . . .Traversal through a string with a loop . . . . . . . . . . . . . . . . . . . .String slices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Strings are immutable . . . . . . . . . . . . . . . . . . . . . . . . . . . .Looping and counting . . . . . . . . . . . . . . . . . . . . . . . . . . . .The in operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .String comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .string methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Parsing strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Format operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Files.Persistence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Opening files.Text files and lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Reading files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

viiiCONTENTS.Searching through a file . . . . . . . . . . . . . . . . . . . . . . . . . . .Letting the user choose the file name . . . . . . . . . . . . . . . . . . . .Using try, except, and open . . . . . . . . . . . . . . . . . . . . . . .Writing files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Lists.A list is a sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Lists are mutable.Traversing a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .List operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .List slices.List methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Deleting elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Lists and functions.Lists and strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Parsing lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Objects and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .List arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Dictionaries.Dictionary as a set of counters . . . . . . . . . . . . . . . . . . . . . . . .Dictionaries and files . . . . . . . . . . . . . . . . . . . . . . . . . . . .Looping and dictionaries.Advanced text parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . .Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

CONTENTSixTuples. Tuples are immutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . Comparing tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tuple assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dictionaries and tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . Multiple assignment with dictionaries . . . . . . . . . . . . . . . . . . . . The most common words . . . . . . . . . . . . . . . . . . . . . . . . . . Using tuples as keys in dictionaries . . . . . . . . . . . . . . . . . . . . . Sequences: strings, lists, and tuples - Oh My! . . . . . . . . . . . . . . . . Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Regular expressions. Character matching in regular expressions . . . . . . . . . . . . . . . . . Extracting data using regular expressions . . . . . . . . . . . . . . . . . . Combining searching and extracting. Escape character. Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Bonus section for Unix / Linux users. . . . . . . . . . . . . . . . . . . . Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Networked programs. HyperText Transport Protocol - HTTP . . . . . . . . . . . . . . . . . . . . The World’s Simplest Web Browser. . . . . . . . . . . . . . . . . . . . Retrieving an image over HTTP . . . . . . . . . . . . . . . . . . . . . . . Retrieving web pages with urllib. Parsing HTML and scraping the web. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Parsing HTML using regular expressions . . . . . . . . . . . . . . . . . . Parsing HTML using BeautifulSoup . . . . . . . . . . . . . . . . . . . . . Reading binary files using urllib . . . . . . . . . . . . . . . . . . . . . . . Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

xCONTENTSUsing Web Services. eXtensible Markup Language - XML . . . . . . . . . . . . . . . . . . . . . Parsing XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Looping through nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . JavaScript Object Notation - JSON . . . . . . . . . . . . . . . . . . . . . . Parsing JSON. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Application Programming Interfaces . . . . . . . . . . . . . . . . . . . . Google geocoding web service . . . . . . . . . . . . . . . . . . . . . . . . Security and API usage. . . . . . . . . . . . . . . . . . . . . . . . . . . Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Object-Oriented Programming. Managing Larger Programs . . . . . . . . . . . . . . . . . . . . . . . . . Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Starting with Programs. . . . . . . . . . . . . . . . . . . . . . . . . . . Subdividing a Problem - Encapsulation . . . . . . . . . . . . . . . . . . . Our First Python Object . . . . . . . . . . . . . . . . . . . . . . . . . . . Classes as Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Object Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Many Instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Using databases and SQL. What is a database? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Database concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Database Browser for SQLite. . . . . . . . . . . . . . . . . . . . . . . . Creating a database table . . . . . . . . . . . . . . . . . . . . . . . . . . Structured Query Language summary . . . . . . . . . . . . . . . . . . . . Spidering Twitter using a database. . . . . . . . . . . . . . . . . . . . . Basic data modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Programming with multiple tables. . . . . . . . . . . . . . . . . . . . .

CONTENTSxi. . Constraints in database tables . . . . . . . . . . . . . . . . . . . . . Retrieve and/or insert a record . . . . . . . . . . . . . . . . . . . . . Storing the friend relationship . . . . . . . . . . . . . . . . . . . . Three kinds of keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using JOIN to retrieve data. Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Visualizing data. Building a Google map from geocoded data . . . . . . . . . . . . . . . . . Visualizing networks and interconnections . . . . . . . . . . . . . . . . . Visualizing mail data. . . . . . . . . . . . . . . . . . . . . . . . . . . .A ContributionsA.Contributor List for Python for EverybodyA.Contributor List for Python for Informatics . . . . . . . . . . . . . . . . .A.Preface for “Think Python” . . . . . . . . . . . . . . . . . . . . . . . .A. . . . . . . . . . . . . . . . .A. .The strange history of “Think Python” . . . . . . . . . . . . . . .A. .Acknowledgements for “Think Python” . . . . . . . . . . . . . .Contributor List for “Think Python” . . . . . . . . . . . . . . . . . . . .B Copyright Detail

xiiCONTENTS

Chapter为什么要学编程?编程是 �因很多, 到为谋 去解决 �别 解决 个问题而获得快乐。本书假定每个 都需要知道怎样编程, 旦学会编程,你就会想要 这个新技能做些什么了。我们的 常 活中计算机 处不在, 到笔记本电脑,小到 �多事情的“私 �构建,就是在不断地问我们 个问题,即“你( )想让我(计算机)下 ext?WhatNext?WhatNext?Figure . : 个 �系统和应 程序,我们 中拿到的成品是 个很有 的个 数字助理(PDA, Personal Digital �的事情。计算机运 速度很快并拥有 �通的语 �么”,那么它就会对我们有 常 �愿完成 些重复性 �得很好的 作通常是那些让我们 类感到 聊、令 头脑 �找出出现频率最 的词是哪 �管你能在短时间内阅读和理解这些 字,但要对它们进 统计就很痛苦了,因为这类问题不是 的 脑擅 解决的。计算机恰好相反,它很难像 样阅读和理解 段 字,但是对 字进 统计并告诉你出现频率最 的词及其出现次数,对计算机而 是 常容易的:python words.pyEnter file:words.txtto 16“个 �to“在本章前三段中 共出现了次。

CHAPTER . 为什么要学编程?事实上,计算机擅 做 类不擅 � “与计算机对话的语 ”。 旦学会这 新语 ,你就可以将枯燥的 �更多的时间去做适合你 �才思、直觉 和创造 ��准备的,专业编程是份 常有前途的 作,可算是物质与精神双丰收。为他 创造有 的、简洁的与智能的程序是 A通常安装了来 许多不同程序员开发的各种软件,每 款软件都想要吸引你的注意 和兴趣。它们尽其所能来满 你的需求,在使 过程中让你获得优质的 体验。在某些情况下,当你选择了 ��作是 � ckMe!PickMe!BuyMe :)Figure . : �了赚钱或者取悦最终 ,而是让我们能更好地处理 �是程序员,也是你所写程序的最终 �让你感到有创新活 的话,到时你的想法也许会发 改变,转向为他 语 之前,我们需要了解 �或者 �SoftwareInput MemoryFigure . : 硬件架构这些组件的 般定义如下:NetworkSecondaryMemory

. . 理解编程 中央处理器(Central Processing Unit ,CPU)是专 为解决“下 �处理速度达到 . GHz,这就意味着CPU每秒会提问 亿次“下 U如此快速地交谈与保持同步。 主存储器(Main Memory) �速度 �后主存储器 的信息也就消失了。 辅助存储器(Secondary Memory)也是 来存储信息的,但是它 ��储信息。常 � 在U盘和便携式 乐播放器上。 输 输出设备(Input and Output Devices)包括屏幕、键盘、 标、麦克 、扬声器以及触摸板等。这些都是 来与计算机进 交互的设备。 如今 多数计算机之间还建 了 络连接,通过 络获取信息。我们可以将 络看成信息存储与检索速度很慢的 �意义上讲, �存储器。这些组件的 作原理细节最好还是交给计算机 商吧。这 只是为了掌握 些术语,在编程时 便提及这些组件。作为 名程序员,你的 作就是利 ��诉它下 步做什么。有时,你要告诉CPU调 主存储器、辅助存储器、 络或输 输出设备。SoftwareInput MemoryNetworkSecondaryMemoryFigure . : Where Are You?你需要成为回答CPU“下 步做什么”的 。但把你压缩到 毫 ,塞 计算机,让你每秒发出 令并进 ��书其他章节中,我们尝试把你培养成 为 名理解编程艺术并具备 定编程能 的 。最后,你会成为 个程序员 ,也许不是专业的。但 种技能:

CHAPTER . 为什么要学编程? 先,需要掌握编程语 (Python)本 ⸺ 熟悉词汇和语法。能够准确地拼写这 新语 中的单词,并且掌握如何使 这 新语 正确地“造句”。 �,通过 �故事的艺术与能 通过写作与反馈得以提 �题即传达的想法。当掌握 种编程语 �程语 ,如JavaScript或者C ,就会容易许多。虽然新的编程语 �学会解决问题的技能,所有编程语 �上 很快,但要能写出 些连贯的程序来解决 个全新的问题,尚需时 磨练。讲授编程就像讲授写作 样。先对程序进 �着逐步编写更复杂的程序。当达到 定 平,你就形成了 的编程 格, �决它。 旦修炼到这个程度,编程就变成 个愉悦且富有创造 �构讲起。第 次阅读时, 定要耐 学习那些简单的例 。.词汇与句 与 类语 �汇,它们有且仅有 个含义。等下你在编程时,你 定义的词汇称为变量。变量命名 常 由,但有 点,你不能使 �上讲,我们训练 只狗时会使 些特殊的词汇, �狗说话时不 ��,“我希望更多的 通过散步来促进健康。”,而 �吧啦吧啦。”这是因为在狗的语 中“散步”是保留字。很多 可能觉得 类和猫之间的语 没有保留字 ewithyield就这么多词汇。Python n会毫 差错地执 �的适 �话(就像 �事情,把想要说的话 引号括起来就可以了。print('Hello world!')这就是我们写出的第 个语法正确的Python语句。我们的句 以函数 print 开头,后 跟 个 本字符串, 单引号括起来。http://xkcd.com//

. . ��Python的 个词汇与 thon对话,测试我们的新语 on。本章包含许多细节,建议查看 www.py e.com, ��动的详细说明和视频演 。当打开终端或者命令 窗口,输 �如下所 :Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25)[MSC v.1900 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information. ‘ ’提 符表 Python解释器在询问,“你希望我下 �话。你需要掌握的是怎样说Python语 ,发起 个对话。举个例 ,你对Python语 最简单的词汇或句 所知,想要使 宇航员的标准 语(喊话)。宇航员在 �居 以下语句对话: I come in peace, please take me to your leaderFile " stdin ", line 1I come in peace, please take me to your leader SyntaxError: invalid syntax 事情进展好像并不顺利。除 你反应迅速,否则这个星球的居 可能会拿 刺向你,向你吐口 ,然后把你放在 上烤,当成晚饭吃掉。幸运的是,旅 时你带了这本书,及时翻到了这 ,再试 次: print('Hello world!')Hello �继续对话: print('You must be the legendary god that comes from the sky')You must be the legendary god that comes from the sky print('We have been waiting for you for a long time')We have been waiting for you for a long time print('Our legend says you will be very tasty with mustard')Our legend says you will be very tasty with mustard print 'We will have a feast tonight unless you sayFile " stdin ", line 1print 'We will have a feast tonight unless you say SyntaxError: Missing parentheses in call to 'print'

CHAPTER . 为什么要学编程?上 的对话 直进展顺利,只到你在使 Python语 的时候犯了 个 常小的错误,Python就 把 n虽然 常复杂与强 ,但在语法上 � 正确的语法。在某种意义上,当你使 别 �之间充当中间 。Python是程序编写者将对话进 下去的 种 式。在阅读完短短 章之后,你将成为Python程序员中的 员,与你的程序使 者进 对话。结束与Python解释器的第 �与这个星球的居 说“再 ”: good-byeTraceback (most recent call last):File " stdin ", line 1, in module NameError: name 'good' is not defined if you don't mind, I need to leaveFile " stdin ", line 1if you don't mind, I need to leave SyntaxError: invalid syntax quit()你会发现前两个错误提 是不同的。由于 if �想说些什么,但句 的语法是错的。跟Python说“再 ”的正确 法是,在交互模式的提 符’ ’后输 quit()。猜出这个命令这可能会花费 些时间,所以 头备本书可能会派上 场。.术语:解释器与编译器Python是 种 级语 ,旨在较为 便地让 类进 读写,让计算进 读取与处理。其他 级语 包括:Java、C CPU 的硬件并不能理解任何 种 级语 。CPU能理解的语 称之为机器语 。机器语 常简单,坦 讲,编写起来 常 聊。它全部由和 000011101010010101101101.虽然机器语 表 看起来很简单,只有 和 ,但它的语法 Python复杂得多。所以,很少有程序员 机器语 �可以编写像Python或JavaScript这样的 级语 ,这些翻译器会将程序转换成机器语 ,再交由CPU执 。因为机器语 �型硬件之间移植。使 级语 �植,通过在另 台计算机上使 不同的编译器,或者重新编译代码, 成 个适合这台计算机的机器语 版本。编程语 的翻译器 体可分为两类:( )解释器 与 ( ) 编译器。

. . ��时解释指令。Python是 种解释器。当交互式执 Python时,输 Python语句,Python就会 即处理它,并做好准备让我们输 下 条语句。Python语句中有 些地 会告诉Python,你想要Python记住等下会 到的 些数据。这时就需要为数据挑选 �� 变量(variable)来代表存储的数据。 6 42 x 6print(x)y x * 7print(y)在这个例 中,我们让Python记住数值 ,并将 赋值给变量x,以便后续使 � print �变量 x 的值并乘以 ,然后将结果赋给新变量 y。最后,打印出变量 y 的当前值。尽管我们 次只输 了 命令,但Python将其视为 个语句序列,后 的语句可以获取前 语句的数据。四句组成的段落以 �是我们写出的第 个简单的多 程序。如上所 ,解释器的本质是进 �放在 个 件中,将 层次的源代码翻译成低层次的机器语 ,然后编译器将 成的机器语 放到 个 件中以便后续执 。如果你使 Windows系统,这些可执 的机器语 分别代表这是“可执 中没有这样的后缀来明确表 件是否是可执 的。如果在 本编辑器中打开 个可执 件,满眼望去完全看不懂: ?ELF A A A @ @ @ @ @ @ @ @ @ B @ C @ A @ @ @\xa0\x82 D H4 @ @ @\x90 ] @ @ @ @ @ @4 @ @ G @( @ @! @ F @ @ @4 @ @ @4\x80 D H4\x80 D H\xe0 @ @ @\xe0 @ @ @ E @ @ @ D @ @ @ C @ @ @ T A @ @ T\x81 D H T\x81 D H S @ @ @ S @ @ @ D @ @ @ A @ @ @ A\ D HQVhT\x83 D H\xe8.机器语 �译器,能够使 Python或C这样的 级语 �论,你应该对Python解释器本 有了 些了解。你应该想问那它 是 什么语 写的?是 编译语 写的吗?当我们输 “python”,究竟发 了什么?Python的解释器是 C语 编写的。你可以访问http://www.python.org ython本 就是 ython,实际是上将 份编译好的Python程序的机器代码拷 ��执 的机器代码很可能位于以下 件夹中:C:\Python35\python.exe

CHAPTER . 为什么要学编程?要成为 名Python程序员,你并不 定的需要知道上述这些。但在 开始,花 �。.编写 个程序在Python解释器中输 命令是体验Python功能 常好的 式,但不建议采 这种 � 本编辑器 把Python指令写到 个 件 ,这个 件称为脚本。 般而 ,Python脚本以.py命名结尾。要执 脚本,你必须告诉Python解释器脚本 你可以像下 这样执 python hello.py:csev cat hello.pyprint('Hello world!')csev python hello.pyHello world!csev “csev ”是操作系统提 符,“cat 看“hello.py” 件的内容,其中包含了 我们调 Python解释器,告诉它从“hello.py” 件中读取源代码,而不是 命令 交互式 地执 n程序 件末尾加上 quit()。Python在读取源代码 件时,到达 件末尾它会 停 ��成特定任务的 组Python语句序列。就算是前 简单的 hello.py 脚本也是 个程序,不过只是 代码的程序罢了,作 并不 。不过从最严格的定义上来说,它是 个Python程序。思考 个可以被程序解决的问题,然后看 �程序的最简单 式。假设,你想对Facebook上的发帖进 社会计算 的研究,并且你感兴趣的问题是 系列帖 中最常 �,然后通读 本,从中寻找最常 的词,但这需要很 ��务,这样会 ��关于 个小丑和 辆 的 �它出现的次数。the clown ran after the car and the car ran into the tentand the tent fell down on the clown and the car

. . 构成程序的小积木然后想象 下,你将要做的是对数百万 �学习Python,编写 个Python程序来统计的话,要 查看单词快得多。 个更好的消息是,我已经写了 个简单的程序来在 本 件中找到最常 �� 些时间。name input('Enter file:')handle open(name, 'r')counts dict()for line in handle:words line.split()for word in words:counts[word] counts.get(word, 0) 1bigcount Nonebigword Nonefor word, count in list(counts.items()):if bigcount is None or count bigcount:bigword wordbigcount countprint(bigword, bigcount)# Code: http://www.py4e.com/code3/words.py你甚 不需要知道Python就可以使 这个程序。你需要通读到本书第 章来完全理解所 到的Python编程技术。你现在是最终 ,只需使 �叹如何让你摆脱繁重的 查看。你只需输 代码,保存到 words.py 件并执 它,或者你也可以从http://www.py e.com/code /下载源码并运 。这个 例充分体现了Python以及这 语 在你(最终 )与我(程序员)之间扮演的中间 。通过Python这 通 语 ,我们可以交流有 的指令序列(即程序),这样任何 在电脑 安装了Python的 都可以使 它。实际上,交流双 � 交流。.构成程序的小积木在接下来的 �句 �学习Python强 �创建有 的程序。程序的构造包含 �仅仅针对Python程序,而是每 种编程语 ,从机器语 到 级语 ,都通 的组成部分。

当打开终端或者命令 窗口,输 python,Python解释器会以交互模式启 动,如下所 : Python