Ebook The practice of computing using python (2nd edition) Part 2

510 1.1K 0
Ebook The practice of computing using python (2nd edition) Part 2

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

(BQ) Part 2 book The practice of computing using python has contents: Functions—QuickStart, lists and tuples, more on functions, dictionaries and sets, more program development, introduction to classes, more on classes, program development with classes, files and exceptions II,... and other contents.

P A R T • Functions and Data Structures Chapter Functions—QuickStart Chapter Lists and Tuples Chapter More on Functions Chapter Dictionaries and Sets Chapter 10 More Program Development This page intentionally left blank • C H A P T E R Functions -QuickStart Function, the exercise, or executing of some office or charge T Blount, Glossographia, 1656, earliest definition of function in the Oxford English Dictionary YOU HAVE SEEN MANY EXAMPLES OF USING PYTHON BUILT-IN FUNCTIONS AND methods In Section 4.3.1, we took at look at how functions work and how we could use them to manipulate string objects In this chapter, you’ll learn how to create your own functions The concept of a function should be familiar from its use in mathematics Functions in programming languages share many of the characteristics of mathematical functions but add some unique features as well that make them more useful for programming One of the main advantages for using functions is that they support divide-and-conquer problem solving Remember divide-and-conquer from Section 3.4.5? This technique encourages you to break a problem down into simpler subproblems, solve those subproblems, and then assemble the smaller solutions into the overall solutions Functions are a way to directly encode the “smaller subproblem” solution You’ll see more about this as we work through this chapter 6.1 W H A T I S A F U N C T I O N ? In mathematics, a function defines the relationship between values Consider the function √ f (x ) ⇒ x If you provide a particular value of x , e.g., x = 4, the function will perform a calculation (here the square root operation) and return the associated value, e.g., Mathematicians term the variable x the argument to the function and say that the function returns the value It is possible for a function to have multiple arguments—for example, a function that calculates multiplication requires two arguments: f (x , y ) ⇒ x ∗ y However, a mathematical 257 258 CHAPTER • F U N C T I O N S - Q U I C K S T A R T function returns only one object Note that the returned object can be a compound object— an object with multiple elements For example, when working with graph paper, each point is represented by by its x and y coordinates, an ordered pair (x , y ) A function that returns an ordered-pair object does indeed return a single value, but it is a value with multiple elements, the x and y values An example of such a function would be the mirror function The mirror function swaps the x and y values of the ordered pair: f (x , y ) ⇒ (y , x ) The notion that the object a function returns can be a compound object is very useful, including in Python Python functions share many of the characteristics of mathematical functions In particular, a Python function: r Represents a single operation to be performed r Takes zero or more arguments as input r Returns one value (potentially a compound object) as output A function is also important because it represents an encapsulation By encapsulation, we mean that the details of an operation can be hidden, providing coarser operations that we as programmers can use without having to understand the function’s internal details A function can represent the performance of an operation without making the reader plow through the details of how the operation is actually performed Consider the sqrt function with respect to encapsulation There are many ways to calculate a square root that vary in accuracy and speed Remember, we saw a particular approach that we called the Babylonian square root approach in Section 3.5 Other implementations exist However, each implementation, each method, represents the “square root” operation Each method takes in an argument and returns that object’s square root As long as the result is correct, we need not be concerned with the details of how the operation is performed That is encapsulation 6.1.1 Why Have Functions? As you progress in learning to program, you’ll move from essential programming elements to important programming elements Selection (if) and repetition (while) are essential programming constructs It is difficult to write any program without using these two essential features Functions, on the other hand, allow us to write better code in the sense that it is more readable Also, because functions allow us to divide programs into smaller pieces, they assist in divide-and-conquer problem solving In that way, functions make programs easier to write Finally, once a function is written, it can be shared and used by other programmers (including ourselves) Thus, functions provide a powerful construct that we can use to make our programs easier to read, write, and maintain From this point on, many of the programming elements we introduce will make some tasks easier and will subsequently make writing and understanding (that is, reading) the program easier You could write programs without them, but those programs would be more difficult to read, write, and maintain 6.2 • PYTHON FUNCTIONS 259 In more detail, functions provide the following features, which help in programming: r Divide-and-conquer problem solving: As we have already mentioned, functions r r r r r divide programs into smaller pieces, an approach that corresponds nicely to a divideand-conquer approach to problem solving (introduced in Section 3.4.5) Abstraction: Functions provide a higher-level interface to operation that the function implements By encapsulating details, functions provide a programmer with a high-level view of the function’s operation that could be implemented in multiple ways—possibly by someone else By analogy, consider how you drive a car It has a simple interface that hides considerable complexity Your car has many options—for example, fuel-injection, turbo, or many others Does the existence of these options change that basic interface you have to the car—i.e., turn the wheel, hit the gas, press the brake? Do you understand how fuel injection provides better performance for your car than a carburetor does? Do you care? You don’t have to know the difference: you simply drive the car Abstraction means that the operation the function represents (drive the car) can be implemented in many ways that not affect the basic car interface The underlying operations can also be changed (upgrade the engine) without changing the interface Reuse: Once a function has been created, it can be reused If you write a function that locates strings in a database, then anywhere that functionality is needed can use that function The more such a function is needed, the “simpler” the code that uses it Sharing: Once your function is well tested, you can distribute it for use by other people Those people can further test the function, refine its capabilities, and through improvement provide a service to everyone in the field Useful functions can be collected into modules for sharing Sharing of modules is one of Python’s strengths, as programmers generously share modules in many diverse areas Security: You hear again and again of security breaches in code: phone companies, computer distributors, software companies, etc One way to battle security issues is the use of functions Small pieces of code can be more easily vetted and security (and other issues) more easily addressed Once they have been approved, they can be used to construct other secure components, which can also be reused, and so on Building securely from the bottom up is one approach to writing secure code Simplification and readability (duplication removal): Because a function provides an encapsulation, it can be used to simplify a program and make it more readable Anywhere that multiple lines of code might be needed to address a problem, a function can replace those lines If the replacement can be done in multiple places, the result is simpler code 6.2 P Y T H O N F U N C T I O N S There are two parts to a Python function, and they correspond to the two parts found in mathematical functions:1 the definition and the invocation The definition defines (creates) the function; the invocation is the application of the function in a program A function Some languages, such as those derived from C (C++, Java, C#), have a third part—the declaration 260 CHAPTER • F U N C T I O N S - Q U I C K S T A R T definition is the second way we have seen to create a name associated with an object in Python, the first being an assignment statement Consider an example function that converts Celsius temperatures to Fahrenheit r First we need a conversion formula: C ∗ 1.8 + 32 r Mathematics has a function invocation: f a hr e nhe it = f (C ) where the definition of the function is: f (C ) = C ∗ 1.8 + 32 r Python has a function invocation that looks very much like the mathematical one: fahrenheit = f(C) but the Python definition looks quite different: def f(celsius float): return celsius float* 1.8 + 32 As in mathematics, C is called an argument of the function The celsius float variable is termed a parameter of the function Upon invoking the function, the argument C’s value is passed to the parameter value celsius float for use in the calculation.2 More detail on the passing of values between arguments and parameters can be found in Section 8.1.1 A function definition begins with the keyword def The Python definition works similarly to an assignment statement By executing a def statement, a new name is created in the namespace and a new object, a function object, is associated with that name As we have observed elsewhere in Python, everything is an object, and functions are no different The def is a compound statement, meaning that it provides a suite of other Python statements and expressions that are part of the function The suite of statements are what will constitute the calculation done by the function object One of the special keywords that can be used in functions is the return statement The return indicates a value that is returned as output from the function invocation A function’s operation ends after a return statement is executed A function may have more than one return statement, but the first one that is executed will end the function’s operation (We have used the phrase “to invoke a function,” but an equivalent and frequently used phrase is “to call a function.”) The general form of a function is shown in Figure 6.1 Let’s create a function to our temperature conversion and use it in a session Note the parts of the function: the def and return keywords as well as the parameter (celsius float) Finally, notice the indentation for the suite of statements, part of the Note that to adhere to our naming convention, the argument C should have been named better, such as celsius float, but we left it as plain C so that it looked more like the mathematical function 6.2 • Function name Must follow variable naming rules def Keyword indicating function is being defined function_name PYTHON FUNCTIONS List of parameters being passed: in parenthesis, comma separated (parameter1, parameter2) statement1 statement2 return value_to_return Return statement indicates the value returned when the function finishes 261 : Suite of the function follows the colon Function suite: contains code to perform some action Indented FIGURE 6.1 Function parts function definition We will discuss the special comment with triple quotes (""") later In essence, it is a brief description of the function and is called a docstring Code Listing 6.1 # Temperature conversion def celsius to fahrenheit(celsius float): """ Convert C e l s i u s to Fahrenheit """ return celsius float * 1.8 + 32 >>> ================================ RESTART ================================ >>> >>> celsius to fahrenheit >>> celsius to fahrenheit(100) 212.0 >>> celsius to fahrenheit(0) 32.0 >>> new fn() Traceback (most recent call last): File "", line 1, in 262 CHAPTER • F U N C T I O N S - Q U I C K S T A R T NameError: name 'new fn' is not defined >>> new fn = "a string object" >>> new fn 'a string object' >>> new fn() Traceback (most recent call last): File "", line 1, in TypeError: 'str' object is not callable >>> Notice that Code Listing 6.1 contains only the function definition—no invocation When the file is run (we press the F5 key in IDLE), the def statement is executed, the name of the function is added to the namespace, and a function object is created That function object is associated with the function’s name in the namespace We can type the name of the function and see that it is associated with a function object We can then invoke (call) the function and see what results are returned Python recognizes to call/invoke a function when a name is followed by parentheses, which may or may not contain a list of arguments It is the parentheses that mark the invocation, and the name adjacent to the parentheses is the function invoked In the session, we converted 100◦ C to 212◦ F and 0◦ C to 32◦ F If the function is not defined, or if the object associated with a name is not a function object, then an error occurs, as is shown in the session 6.3 F L O W O F C O N T R O L W I T H F U N C T I O N S Functions introduce a new flow of control model Up to this point, a program has essentially been a series of statements and expressions that are executed in the order in which they appear in the file Some of the statements introduce local control paths within those statements, such as with selection or repetition, but the flow remains sequential in the file With functions, we create a set of small, independent subprograms that can be used to construct a larger program In short, the flow of control with functions is to flow from the invocation (call) in the calling program, to the function itself, and then back to the calling program with the function’s return value being made available to the calling program Control within a function remains sequential: one statement after another along with local control statements such as if and while For every program, there is usually one “main” part where execution begins After that, the flow of control is based on the order of both statements and functions In particular for functions, operation of a function is determined by when it is invoked, not when it is defined Functions can be defined anywhere in the program file, as long as they are defined before they are invoked Functions must be defined before use because the function name must be placed in the namespace before it can be called Figure 6.2 shows an example of function control flow 6.3 • FLOW OF CONTROL WITH FUNCTIONS 263 Main program statement Call fahrenheit = celsius_to_fahrenheit(25) Function def celsius_to_fahrenheit(celsius): statement Retu statement rn val = celsius * 1.8 + 32 return val FIGURE 6.2 Function flow of control 6.3.1 Function Flow in Detail Consider two programs: the caller, the program presently executing, and the function In this example, the caller is the main program, the program where execution begins A caller executes its statements until it encounters a function invocation, celsius to fahrenheit (25) in Figure 6.2 At that point, the caller temporarily suspends, and the function begins Thus, one program is suspended (the caller) waiting for a result from the now executing function When the function finishes execution, the suspended caller receives the return value from the function and the main program (caller) resumes execution from that point Because the function is essentially a new program, the function gets its own namespace when it begins execution Any object that gets created and given a name (by assignment, by a def, etc.) within the function is placed in the function’s separate namespace, not the main program’s (caller’s) namespace If a new name is created in the function that is the same as a name that existed in the caller’s namespace, the newly created association is used in the function This protocol has some interesting consequences, which we will explore in Section 8.1.1 6.3.2 Parameter Passing VideoNote 6.1 Simple Functions Parameter passing is the passing of values from a calling program to a function, so that the function can perform its operation You will remember that the function celsius to fahrenheit had a single argument, called C The function had a single parameter called celsius float Parameter passing is the passing of values from argument to parameter Parameter passing is done just before the calling program suspends The caller associates its argument values to the corresponding function parameter in the function object In Figure 6.2, the argument value 25 is associated with the parameter celsius The parameter is then defined in the function’s namespace and associated with the value of its corresponding argument After that, function operation begins 264 CHAPTER • F U N C T I O N S - Q U I C K S T A R T Argument values are typically passed to parameter names in the order they are listed.3 The names of the corresponding argument and parameter need not match Only the order matters: the first argument value is passed to the first parameter, the second argument value to the second parameter, and so on The number of arguments and parameters must match.4 Again, after values are passed, the function then begins execution During function execution, if a return statement is executed, the function ends and the return value is provided to the caller (“return” arrow in Figure 6.2) For example, fahrenheit = celsius to fahrenheit(25) assigns the returned value to the main program variable fahrenheit as shown in Figure 6.2 After the function ends, the caller continues Code Listing 6.2 is a sample program with a function that takes in a Celsius temperature to convert to Fahrenheit Code Listing 6.2 # Conversion program def celsius to fahrenheit(celsius float): """ Convert C e l s i u s to Fahrenheit """ return celsius float * 1.8 + 32 # main part o f the program print("Convert Celsius to Fahrenheit.") celsius float = float(input("Enter a Celsius temp: ")) 10 # c a l l the conversion function 11 fahrenheit float = celsius to fahrenheit(celsius float) 12 # print the returned value 13 print(celsius float," converts to ",fahrenheit float," Fahrenheit") >>> ================================ RESTART ================================ >>> Convert Celsius to Fahrenheit Enter a Celsius temp: 100 100.0 converts to 212.0 Fahrenheit >>> ================================ RESTART ================================ >>> Convert Celsius to Fahrenheit Enter a Celsius temp: 0.0 converts to 32.0 Fahrenheit Python also has other ways to pass argument values to parameters See Chapter In Chapter you will learn about default values, which allow fewer arguments than parameters 750 INDEX Asterisks single, 668–669 two, 670 & operator, 407 Attributes, 53 class, 483 class, changing, 484–485 instance, 495 private versus public, 507–508 Augmented assignment operator, 65–67 B Babylonian square root algorithm, 154–155, 258 Backslash, 41, 46, 180, 181 Bardeen, John, 19 Bar graph of word frequency example, 425–427 Bar graphs, 729 Base case, 650, 654 Basketball lead example, 86–90 Basketball program, example of testing, 636–639 Binary data, 26–28 Binary decision/selection, 81 Binary files, 227 Binary operators, 407 Bits, 29 bool, 57, 104 Boole, George, 103–104 Boolean operators, 83, 109–110 operators, example of, 111–113 relational operators, 104–108 type, 57, 83 variables, 104 Braces, curly, 57, 58, 385 Brackets, square, 57, 182, 200, 283, 385 Branch instruction (BRZ), 142–143 Brattain, Walter, 19 break statement, 123–127, 131 Breast cancer classifier example See Program development, breast cancer classifier example Broadcasting, 737 Bubble Sort, Buffer, 228–229 Bugs and debugging, 632–633 Built-ins, 422 class and instance, 481–482 data types, 693 modules, 693–694 bytearray, 693 Bytes, 29, 693 C Calling/ invoking See Invoking/calling Cantor, Georg, 405 CapitalWords approach, 483, 740 Carriage return, 181, 596 Case, changing, 211 Central Processing Unit (CPU), 24 Chained relational operators, 108 Chaining methods, 197 Characters non-printing, 181 representing, 29–30 choice(sequence), 692 chr(), 182 Circumference program, 38–41 Class See also Instance; Program development, predator-prey simulation attributes, 483 attributes, changing, 484–485 built-in, 481–482 definition, 483 definition, format of, 482 elements in, deciding on, 493 hierarchy, 545–547 init (), 494–495 instance-of relationship, 485–488 introspection, 520–522 is-a relationship and class hierarchy, 545–547 keyword, 483 name, 483 properties, 684–688 random numbers, 691–693 rational number (fraction), example, 518–520, 526–539 scope rules, 486–488 serializing an instance, 688–691 simple example, 477–478, 482–484, 493–494 str (), 496–497 use of term, 479–480 INDEX Class designer point class example, 499–506 role of, 498–499 Classifier (classification) See also Program development, breast cancer classifier example algorithm, 441–462 classify test set(), 456–460 Class separation value, 441 clear(), 411 Closing files, 228, 599 Code, use of interactive, 706–707 Code point, 217 Collatz conjecture, 136 Collection operations dictionaries and, 386–387 iterator objects and, 672–673 Collection type, 57, 93, 693 Colons, use of, 183–184, 186, 187, 202 Color, 140 Turtle Graphics, 714–717 Commas, use of, 284, 321–322 Comma-separated value (CSV) format See CSV (comma-separated value) format Comments designating, 40 readability and, 162–163 role of, 46 Compound statement, 84 Comprehension dictionary and set, 424–425 list, 337–339 Computation defined, 13 efficiency of, evolutionary, 15–16 human brain, 14–15 minimal, 142–143 theory of, 4–5 Computer architecture, 24–26 defined, 13–14 development of, 18–24 human, 17–18 Computer languages, choosing, 11 Computer processing unit (CPU), 21, 22 Computer science applications, defined, fields, 4–6 importance of, 3–4 Concatenation string, 189–190 + symbol, 189–191 Condition, 82 Consistency, 517 Constructors, 59–61 Context, 618 Continuation, 45–46 continue statement, 127–129, 131 Control See also Recursion; Repetition; Selection functions and flow of, 262–273 nesting, 134–135 strings and, 205–208 try-except flow of, 234–237 copy(), 389, 411 Copying dictionaries and shallow, 389 lists, 313–320 shallow versus deep, 316, 318–320 Copy slice, 187, 313–314, 317 Correctness program, 164–165 testing for, 635 count(), 292 cp1252, 399 CSV (comma-separated value) format, 242, 398–400 defined, 601 module, 601–602 reader, 602–603 updating grades example, 603–605 writer, 603 Current file position, 597–598 D Data binary, 26–28 limits, 28–29 plotting, with pylab, 137–141 quantities, 32–34 value, interpreting, 31–32 751 752 INDEX Data structures, See also Dictionaries; Lists; Sets; Strings defined, 324–325 example, algorithm, 327–337 examples of, 325–327 stacks, 657–661 Data types, built-in, 693 Debugging, 632–633 decimal module, 56 Decision See Selection Declaration of Independence, compared with the Gettysburg Address, 412–416 Decorators, 678–684 Deep copy, shallow versus, 316, 318–320 Default arguments, 197 Default values, 365–368 Deficient numbers, 95 Definition, functions and, 259–262 def statement, 260–262, 358, 359 Delimiters See Punctuators Dependencies, 722–723 deque, 693 Descriptor codes, 202–203 Design errors, 632 Developer errors, 641–643 dict, 57, 385, 386 dict , 369 Dictionaries, 57, 326 collection operations, 386–387 comprehension, 424–425 creating, 385, 424 defined, 383–384 example of, 384 indexing and assignment, 385–386 key types, 386 methods, 387–390 mutable, 385 other terms for, 383 periodic table example, 398–404 word count example, 391–398 zip operator to create, 424 difference method, 408–409 Dijkstra, Edsger, 633 dir(), 371, 483 Directory structure, 606–607 Directory tree, 606, 607 discard(element), 411 Disk, 25 size, 32–33 Divide-and-conquer problem solving, 168, 257, 259, 437–438, 539 functions for, 401–404 Division, 62, 63, 64 Divisors, summing,100–101 doc , 369, 371 Docstrings, 261, 371 doctest, 643–646 Dot notation, 196, 197, 293 Drawing See Turtle Graphics dump(obj, file), 688 dumps(obj), 688 Dynamic testing, 634 E Early exit, 124 Edison, Thomas, 632 Efficiency, 325 Elements (Euclid), 530 else clause, 123, 131, 618 EMC, 33 Empty list, 284 Empty object, 104 Empty set, 405 Encapsulation, 194, 258 object-oriented programming and, 479, 506 Enclosed namespaces, 422–423 Encoding, 217 ENIAC, 18 Enthought Python Distribution (EPD), 722 eq (), 527 Equality, 105–108 reducing rational numbers and, 536–539 Equal to, 83, 105 Errors See also Exception handling; Testing bugs and debugging, 632–633 checking, 245–246 design, 632 developer, 641–643 handling, 232–237 IOError, 233, 640–641 names, 233 out of range, 183 INDEX philosophy concerning, 616–618 runtime, 232, 632 StopError, 671 StopIteration, 674 syntax, 232, 632 try-except construct, 233–234, 235–237 try-except flow of control, 234–235 user, 127, 639–641 ValueError, 233 Escape character, 180 Euclid, 530 evens(), 363, 365 Events, 616 Exabytes (EB), 33, 34 Exception handling, 233, 235–237 basic, 612 creating your own, 621–622 else clause, 123, 131, 618 events, 616 example, 613–616 finally clause, 618–620 multiple, 616 philosophy concerning, 616–618 raising, 620–621 try-except suite, 612–616 Exponentiation operator, 41 Expressions, 43–44 extend(C), 293, 294 F factorial(), 651–654 Fetch-decode-execute-store cycle, 25–26 Fibonacci sequence, 652–654 file handle.close(), 228, 250 file handle=open(), 228, 250 Files analysis example (Gettysburg address), 305–310 closing, 228, 599 CSV file format, 601–605 current position, 597–598 defined, 227 descriptor or stream, 228 input-output, 229 modes, 231 moving around in, 597–599 new line format, 596–597 object, 228 opening, 227–228 overwriting, 231 reading, 227–229, 593–595 reading and writing text, in a program, 230–231 review of, 591–593 with statement, 599–600 writing, 229–230, 595–596 filter(), 677–678 Final grade example, determining, 371–375 finally clause, 618–620 find(), 196, 197, 205–208 Firefox, 12 Flag designs based on religion, example, 470–471 Floating-point numbers, 56 Floating-point operators, 63 Floating-point precision descriptor, 204 Floating Point Unit (FPU), 26 float type, 56 Formatting alignment descriptors, 202, 203–204 command, 202 description of, 213–216 descriptor codes, 202–203 floating-point precision descriptor, 204 output for strings, 201–205 width descriptors, 202, 203–204 for statement/loop, 120–121 else clause, 131 break statement, 131 continue statement, 131 equivalence of, 134 iteration, 91, 93–94 range(), 131–134 sets and, 406 view objects, 388–389 when to use, 134, 673 Fractions, 28, 56–57 See also Rational number (fraction) example adding, 529–535 frozenset, 693 Functional programming, 676 Functional programming languages, 649 Function calls, stacks and, 659–661 Functions See also specific one annotations, 370–371 argument list, 67 753 754 INDEX Functions (Contd.) arguments, 257–258, 260 decorators, 678–684 defined, 40, 135, 194–195, 257–258 definition and invocation, 259–262 for divide-and-conquer, 401–404 example, determining final grade, 371–375 examples, 265–273 flow of control, 262–273 invoking/calling, 195, 259–262, 273 lists and, 289–290 name, 67, 358–359 names associated with, 369 namespaces, 357–359 as objects, 369–371 os (operating system) module, 608–609 parameter, 260, 263–265 parts of, 261 passing information from arguments to parameters, 359–361 passing mutable objects, 361–363 reasons for, 258–259 returning complex objects, 363–364 return statements, 274–275 scope, 357–358 string, 195, 201–205 when to use, 273–274 G Generators, 673–676 Genetic algorithms, 16 get(), 390 Gettysburg address, file analysis, 305–310, 393–398 compared with the Declaration of Independence, 412–416 Gigabytes (GB), 32 Global namespace, 418–420 global statement, 421 Google Style Guide, variable names, 50 Graph theory, Greater than or equal to symbol, 83, 410 Greater than/right symbol, 83, 214 Greatest common divisor (GCD), 529–532 Group development, 548 Grouping statements, 45, 84–85 H Hailstone sequence example, 136–137 Half-open range, 184 Halting problem, Hard drive, 25 Haskell, 649 Header, 84 Heron of Alexandria, 154 Hexadecimal, 55 Hierarchy, 545–547 Histograms, 730 Hopper, Grace, 632–633 Howard, Michael, 234 How to Solve It (P´olya), 165 Human brain, 14–15 Hungarian notation, 59 I IBM, 21, 32 id(), 53 IDC Digital Universe study, 33 Identification number, 53, 54 IDLE, 38, 39 indentation and, 45 matplotblib and, 725–725 method names and arguments, determining, 198–200 if-elif-else statement, 116–120 if-else statement, 85–86, 116 if statement, 83–85, 116 Images, 30–31 Immutable strings, 193–194 import command, 67 Import files, 39 import module, 43 variation using from, 519–520 Indentation, 45, 84–85, 741 readability and, 163 Index assignment, 291 character, 182 index(), 292 Indexing dictionaries, 385–386 lists, 286–287 INDEX operator, 182, 385 strings, 183–187 Infinite loop, 121 Infinite recursion, 650 Inheritance changing code using, 552–554 finding, 544–547 is-a relationship and class hierarchy, 545–547 object-oriented programming and, 479, 506–507 Standard Model, 549–554 init (), 494–495, 526, 528 Initialization, 121 in operator, 192–193, 211, 406 Input, program design and, 171–173 input function, 40 Input/output devices, 25 file streams, 229 insert(i, x), 293, 294 Instance See also Class attributes, 495 built-in, 481–482 changing, 497, 509–510 creating, 483–484 init (), 494–495 initializing, 495–496 printing, 496–497 serializing an, 688–691 str (), 496–497 use of term, 479–480 instance-of relationship, 485–488 Instructions, 43 Integer operators, 61–63 Integers, 26, 55–56 Integrated circuits, 20–21 Integration testing, 634 Intel, 21, 22, 635 Internet, Interpreted language, 42 intersection method, 407 int function/type, 40–41, 55 Introspection, 520–522, 540–542 Invocation, functions and, 259–262, 366 Invoking/calling functions, 195, 259–262, 273 methods, 196 IOError, 233, 640–641 is-a relationship and class hierarchy, 545–547 isinstance(), 521–522 items(), 387–390 iter (), 671 Iterables lists, 286, 290 range, 133 string, 187–188 iter(a collection), 672 iter(an iterator), 671 Iteration, 91, 93–94 Iterator objects, 671–673 J join(), 296–297 K key, 57 keys(), 387–390 Key types, dictionaries and, 386 Keywords, 47 arguments, multiple, 669–670 class, 483 parameters as, 366 Kilby, Jack, 20–21 Kilobytes (KB), 32 Knuth, Donald, 153–154 L lambda expression, 676–677 Last In, First Out (LIFO), 657 Leading whitespace, 45 Leading zeros, 55 Least common multiple (LCM), 529–530 LeBlanc, David, 234 LEGB rule, 416–417, 486 len(), 195, 265–267, 289, 406 Less than/left symbol, 83, 214 Less than or equal to symbol, 83, 410 Linux, 12 Lisp, 649 755 756 INDEX Lists, 57 See also Tuples appending itself, 315 converting back and forth between strings and, 296–297 copying, 313–320 creating, 283–284 defined, 283 difference between strings and, 283, 290–294 empty, 284 example, anagrams, 299–304 example, comprehension, 337–339 example, file analysis (Gettysburg address), 305–310 functions and, 289–290 indexing and slicing, 286–287 iteration, 286, 290 list of, 285 methods, 292–294 mutable, 290–292, 310–321 naming, 284 nesting, 285 operators and, 287–289 plotting using, 138–140 sorting, 297–299 Literals, 48 load(file), 688 Local assignment rule, 420–421 Local namespace, 357–359, 417–418 Logo, 709 Loops break statement and non-normal exit, 123–127 control, 93 control variable, 121 for, 91, 93–94, 120–121 infinite, 121 initialization, 121 sentinel, 130 while, 91–93, 120–122 lower(), 211, 309 M main(), 374, 393, 396, 412, 413 make averages(), 453 make test set(), 450–451 make training set(), 446–450 map, 57, 181–182 dictionary, 383 map(), 677–678 Markers, 140 math.cos(), 68 Mathematical operations, precedence of, 64–65 math.fabs(), 68 math.hypot(), 68 math module, 67–68 math.pow(), 68 math.sin(), 68 math.sqrt(), 68 matplotlib command line, 725 command line, Windows, 726–727 defined, 721 getting, 722–726 IDLE and, 724–725 plotting data with, 137–141 working with, 727–731 Matrix, 327 max(), 289 Megabytes (MB), 32 Memory, main/random access, 24 Methods arguments, determining, 198–200 arguments, optional, 197 chaining, 197 defined, 195–196 dictionary, 387–390 invoking/calling, 196 list, 292–294 names, determining, 198–200 nesting, 197–198 object, 488–493 set, 407–410 string, 195–198, 200 min(), 289 mirror(), 258, 363–364 Mixed operations, 63–64 Modules built-in, 693–694 csv, 601–602 defined, 40, 43, 67 Internet, 694 math, 67–68 os (operating system), 606–612 Moore, Gordon, 22 Multiplication, 41, 63 Music, 31 INDEX Mutable dictionaries, 385 lists, 290–292, 310–321 objects and references, 310–321 passing mutable objects, 361–363 sets, 406 Numbers example of classifying, 99–102 range(), 131–134 Numeric types, 55–57 NumPy module, 340, 723–724, 732–733 O N name , 369 namedtupel, 693 Namespaces, 50, 262, 311 built-ins, 422 enclosed, 422–423 global, 418–420 global statement, 421 local, 357–359, 417–418 local assignment rule, 420–421 scope and, 416 Naming class, 483 conventions, 739–741 functions, 67, 358–359 Hungarian notation, 59 lists, 284 objects, 48–49 parameters, 367 readability and, 160–162 recommendations on, 49 variables, 50–52 Nesting control and, 134–135 lists, 285 of methods, 197–198 Netflix, 33 Network, 25 Neumann, John von, 24 New line format, 596–597 Newton’s method, 155 next (), 671 next(an iterator), 671 Non-empty object, 104 Non-normal exit, 123–127 Non-printing characters, 181 Not equal to symbol, 83 not operator, 109–110 Null set, 405 Object-oriented programming (OOP), 676 characteristics of, 478–480, 506–507 group development, 548 public versus private, 507–508 Objects functions as, 369–371 generator, 675 identity and attributes, 53 iterator, 671–673 mutable, 310–321 naming, 48–49 passing mutable, 361–363 passing references, 375 returning complex, 363–364 scope rules, 486–488 string, 180 types, 53–55, 58–59 view, 388–389 Octal, 55 Onion approach, 168–169 Opening files, 227–228 Open source model, 12–13 Operations augmented assignment, 65–67 object, 53 precedence of mathematical, 64–65, 737 shortcut, 65–66 Operators Boolean, 83, 109–110 exponentiation, 41 floating-point, 63 indexing, 182, 385 integer, 61–63 list of, 47 lists and, 287–289 mapping, to special methods, 524–525 mixed operations, 63–64 overloading, 61, 190, 523–526 precedence of, 64–65, 110–111, 737 757 758 INDEX Operators (Contd.) rational number (fraction), 518–520 relational, 104–108 ternary, 339 tuples, 322–323 Operators, string comparison, 191–192 + (concatenation), 189–190 determining when + means addition or concatenation, 190–191 in, 192–193 lists and, 287–289 ∗ (repetition), 189–190 or circuit, 19 ord(), 182, 217 OrderedDict, 693 Ordering, 294 or operator, 109–110 os (operating system) module directory (folder) structure, 606–607 example, 609–612 functions, 608–609 os.chdir(), 608 os.getcwd(), 608 os.listdir(), 608 os.path(), 608 os.walk(), 609 Out of range error, 183 Output, 170–171 Overloading, operator, 61, 190, 523–526 Overwriting files, 231 P Palindromes, 210–213 Parallel processing, 5–6 Parameters, 260 default values and passing, by name, 365–368 having a varying number of, 668–670 as keywords, 366 naming, 367 passing, 263–265 passing information from arguments to, 359–361 Parentheses, 65 parse element(), 401, 402–404 parse line(), 373–374 Passing by value or by reference, 375 information from arguments to parameters, 359–361 mutable objects, 361–363 of object references, 375 parameters, 263–265 pass statement, 129–130, 399 Password manager example, 622–625 PEP (Python Enhancement Proposal) naming conventions, 49, 740–741 Perfect number, example, 95–99, 119–120 Periodic table example, 398–404 Petabytes, 32–33 pickle module, 688–691 Pie charts, 731 Pixels, 30–31 plot command, 727–728 Plotting arrays and range(), 340–341 data with pylab/matplotlib, 137–141 properties, 728 trigonometric functions, 342–343 Poker hands, counting example, 238–249 P´olya, George, 165 Polymorphism, object-oriented programming and, 479, 507 pop(), 293, 294 Pop operation, stack, 657–659 Positional arguments, 668–669 Post-coding, 634 Pound sign, 40, 214 Powers of or 10, 32 Precedence of mathematical operations, 64–65, 737 of operators, 64–65, 110–111, 737 Precision descriptor, 202, 204 Precoding, 634 Predator-prey simulation See Program development, predator-prey simulation pretty print(), 393, 395–396, 412, 414 print statement, 41, 496 comment and uncommenting in, 532 Private attributes, 507–508 Problem solving, divide-and-conquer, 168, 257, 259, 401–404, 437–438, 539 program designing, 165–169 Procedural programming, 676 INDEX Procedures, 274 process line(), 393, 394–395, 412, 413 Processor, 24 Program development, breast cancer classifier example basic information, 438–441 classifier algorithm, designing, 441–462 classify test set(), 456–460 data structures, 445 divide-and-conquer, 168, 257, 259, 401–404, 437–438 file format, 445–446 make averages(), 453 make test set(), 450–451 make training set(), 446–450 report results(), 460–462 sum lists(), 452–453 testing, 455–460 top-down refinement, 438 train classifier(), 451–452, 453–455 training versus testing, 462–466 utility functions for manipulating lists, 452 Program development, examples flag designs based on religion, 470–471 S&P 500 predictions, 467–470 tag clouds, 466–467 Program development, predator-prey simulation animal object, 565–568 breeding, eating, and keeping time, 576–584 filling the island, 569–572 graphing population size, 585–586 how many times to move, 584–585 island class, 563–565 movement, adding, 572–575 object diagram, 569, 570 overview of, 561–562 predator and prey classes, 568–569 rules, 562 simulation using object-oriented programming, 563 time simulation loop, 575–576 Programming difficulty of, 6–9 functional, 676 object-oriented, 478–480, 506–507, 676 procedural, 676 role of, 10–11 rules, 37 what constitutes good, 9–10 Programs algorithms versus, 155–157 changing, 99 correctness, 164–165 defined, 10, 159–165 design, example, 169–177 designing, 165–169 parts of, 43–49 readability, 159–163 robustness, 163–164 skeleton, 100 Properties, 684–688 Public attributes, 507–508 Punctuators (delimiters), list of, 47 Push operation, stack, 657–659 py suffix, 38 pylab, plotting data with, 137–141 Python history of, 697 making a program, 702–705 obtaining, 698–699 philosophy, 12 platform and version, 723 reasons for using, 11–13 shell, use of, 43 starting up, 699–700 working with, 700–701 Python Enhancement Proposal (PEP) naming conventions, 49, 740–741 Python Package Index, 694 Python 3, 697–698 Q Queue, 326 Quick Sort, Quotation marks single or double, 43, 57, 180 triple, 180–181 Quotient, 62, 63 R Raising exceptions, 620–621 randint(a,b), 692 random(), 692 759 760 INDEX Random numbers, 691–693 range(), 131–134 arrays and, 340–341 half-open, 184 Range of numbers, 99–100 Rational number (fraction) example, 518–520, 526 assignment, 535 equality and reducing, 536–539 fractions, adding, 529–535 introspection, 520–522, 540–542 making the class, 527–529 methods used, 527 mixed-type comparisons, 544 reversed methods, using, 542–544 testing problems, 539–540 read(), 593, 595 Readability, 159–163 Reader, CSV, 602–603 Reading files, 227–229, 593–595 example of, in a program, 230–231 readline(), 593, 594 readlines(), 593, 594–595 read table(), 401–402 Recursion converting to nonrecursion, 664 defined, 649–651 factorial(), 651–654 Fibonacci sequence, 652–654 how it works, 656–661 infinite, 650 Sierpinski triangles, 663–664 step, 650 of a string, 654–656 tree, 661–663 reduce(), 677–678 Refactoring, 119, 302, 365, 618–620 References, 359, 361 mutable, 310–321 object, 375 Relational operators, 104–108 Remainder, 62 remove(x), 293, 294 remove(element), 411 Repetition, 90 for statement, 91, 93–94, 120–121 ∗ (string operator), 189–190 while statement, 91–93, 120–121 replace(), 212–213 report results(), 460–462 repr (), 527, 528 Returning complex objects, 363–364 return statements, functions and, 260, 274–275 Return value, 43–44, 68, 195 reverse(), 293 Robustness, 163–164 Rossum, Guido van, 697 Routers, Runtime errors, 232, 632 S sample(sequence, num), 692 S&P 500 predictions, example, 467–470 Scheme, 649 Scope functions and role of, 357–358 global namespaces, 418–420 global statement, 421 local assignment rule, 420–421 local namespaces, 357–359, 417–418 namespaces and, 416 rules for objects, 486–488 search rule for, 416–417 seed(obj), 692 seek(n), 598 Selection binary, 81 Boolean, 83, 103–113 break statement and non-normal exit, 123–127, 131 continue statement, 127–129, 131 control flow, 82 else clause, 123, 131 example, basketball lead, 86–90 example, classifying numbers, 99–102 example, finding perfect numbers, 94–99, 119–120 for statement, 91, 93–94, 120–121, 131–134 if-elif-else statement, 116–120 if-else statement, 85–86, 116 if statement, 83–85, 116 pass statement, 129–130 repetition, 90–94, 120–122 sentinel loop, 130 while statement, 91–93, 120–121, 130 self, 495, 501, 503, 505, 528 Self- referencing, 315 INDEX sentinel loop, 130 Sequence, 57, 93 strings as, 180, 182–183 sub-183 Serializing an instance, 688–691 set(), 405 SET constructor, 405 Sets, 58, 93, 326, 404 applications, 411–416 comprehension, 424–425 defined, 405 empty or null, 405 history of, 405 methods, 407–410 subset and superset, 409–410 Sets, Python creating, 405–406 mutable, 406 operations, 406 Shallow versus deep copy, 316, 318–320 Shanks, William, 17 Shannon, Claude, 104 Shockley, William, 19 shuffle(sequence), 692 Side effect, 44 Sierpinski triangles, 663–664 Sign format, 214 Simonyi, Charles, 59 Sine wave, plotting, 140–141 Skeleton, 100, 170, 443 Slice assignment, 291 Slicing lists, 286–287 strings, 183–187 Smartphones, Social networking, Software engineering, 6, 548 sort()method, 293, 294, 397 sorted()function, 297–299 Spaces (spacing), 85 special sum(), 522 split(), 209–210, 295–296 Square roots, calculating, 154–155, 258 Stacks, 657–661 Standard Model, 549–554 Stars single, 668–669 two, 670 761 Statements compound, 84 defined, 44 grouping, 45, 84–85 Static testing, 634 StopError, 671 StopIteration error, 674 Stop words, 397, 467 str, 57, 180 str (), 368, 496–497, 527, 528 string(), 195 String operators comparison, 191–192 + (concatenation), 189–190 determining when + means addition or concatenation, 190–191 in, 192–193 lists and, 287–289 ∗ (repetition), 189–190 Strings comparing, 191–192 control, 205–208 converting back and forth between lists and, 296–297 defined, 40–41, 179 difference between lists and, 283, 290–294 example, palindromes, 210–213 example, reordering person’s name, 208–210 formatted output for, 201–205 formatting, 213–216 functions, 195, 201–205 immutable, 193–194 indexing and slicing, 183–187 iterable, 187–188 methods, 195–198, 200 non-printing characters, 181 objects, 180 operators, 189–194 recursive, 654–656 representation, 181–182 as a sequence, 180, 182–183 triple-quote, 180–181 type, 57 strip(), 268–269, 309 sub (), 527 Subsequences, 183 Subset, 409–410 Subtraction, 63 Suite, 84 762 INDEX sum(), 134, 289 sum lists(), 452–453 Summing divisors, 100–101 Superset, 409–410 Swapping, 115–116 Switches, 18–19 Symbols + (addition), 63, 191 alignment, 214 = (assignment statement), 40, 50, 65–66, 105 ∗ (asterisk or star), 668–669 ∗∗ (asterisks or stars), 670 & operator, 407 \(backslash), 41, 46, 180, 181 Boolean operators, 83 {} (braces, curly), 57, 58, 385 [ ] (brackets, square), 57, 182, 200, 283, 385 ∧ (center), 214, 409 : (colon), 183–184, 186, 187, 202 , (comma), 284, 321–322 + (concatenation), 189–191 / (division), 62, 63, 64 (dot notation), 196, 197, 293 == (equal to), 83, 105 \(escape character), 180 ** (exponentiation), 41, 63 floating-point operators, 63 = (force fill between sign and digits), 214 |operator, 408 > (greater than/right), 83, 214 >= (greater than or equal to), 83, 410 integer operators, 61–63 < (less than/left), 83, 214

Ngày đăng: 16/05/2017, 09:31

Từ khóa liên quan

Mục lục

  • Cover

  • Title Page

  • Copyright Page

  • SUPPLEMENTARY MATERIAL

  • ACKNOWLEDGMENTS

  • CONTENTS

  • PREFACE

  • PART 1 THINKING ABOUT COMPUTING

    • Chapter 0 The Study of Computer Science

      • 0.1 Why Computer Science?

      • 0.2 The Difficulty and Promise of Programming

      • 0.3 Choosing a Computer Language

      • 0.4 What Is Computation?

      • 0.5 What Is a Computer?

      • 0.6 The Modern, Electronic Computer

      • 0.7 A High-Level Look at a Modern Computer

      • 0.8 Representing Data

      • 0.9 Overview of Coming Chapters

      • PART 2 STARTING TO PROGRAM

        • Chapter 1 Beginnings

          • 1.1 Practice, Practice, Practice

          • 1.2 QuickStart, the Circumference Program

          • 1.3 An Interactive Session

          • 1.4 Parts of a Program

Tài liệu cùng người dùng

Tài liệu liên quan