Text
stringlengths
1
9.41k
Omit directory paths and file suffixes in import statements (e.g., say import mod, not import mod.py).
(We discussed module basics in Chapter 3 and will continue studying modules in Part V.) Because modules may have other suffixes besides .py (.pyc, for instance), hardcoding a particular suffix is not only illegal syntax, but doesn’t make sense. Any platform-specific directory path syntax comes from module search path s...
Because this is the last chapter in this part of the book, we also reviewed common coding mistakes to help you avoid them. In the next part of this book, we’ll start applying what we already know to larger program constructs: functions.
Before moving on, however, be sure to work through the set of lab exercises for this part of the book that appear at the end of this chapter.
And even before that, let’s run through this chapter’s quiz. ###### Test Your Knowledge: Quiz 1. When should you use documentation strings instead of hash-mark comments? 2.
Name three ways you can view documentation strings. **|** ----- 3. How can you obtain a list of the available attributes in an object? 4.
How can you get a list of all available modules on your computer? 5. Which Python book should you purchase after this one? ###### Test Your Knowledge: Answers 1.
Documentation strings (docstrings) are considered best for larger, functional documentation, describing the use of modules, functions, classes, and methods in your code.
Hash-mark comments are today best limited to micro-documentation about arcane expressions or statements.
This is partly because docstrings are easier to find in a source file, but also because they can be extracted and displayed by the PyDoc system. 2.
You can see docstrings by printing an object’s __doc__ attribute, by passing it to PyDoc’s help function, and by selecting modules in PyDoc’s GUI search engine in client/server mode.
Additionally, PyDoc can be run to save a module’s documentation in an HTML file for later viewing or printing. 3.
The built-in dir(X) function returns a list of all the attributes attached to any object. 4.
Run the PyDoc GUI interface, leave the module name blank, and select “open browser”; this opens a web page containing a link to every module available to your programs. 5. Mine, of course.
(Seriously, the Preface lists a few recommended follow-up books, both for reference and for application tutorials.) ###### Test Your Knowledge: Part III Exercises Now that you know how to code basic program logic, the following exercises will ask you to implement some simple tasks with statements.
Most of the work is in exercise 4, which lets you explore coding alternatives.
There are always many ways to arrange statements, and part of learning Python is learning which arrangements work better than others. See Part III in Appendix B for the solutions. 1.
Coding basic loops. a. Write a for loop that prints the ASCII code of each character in a string named ``` S.
Use the built-in function ord(character) to convert each character to an ``` ASCII integer. (Test it interactively to see how it works.) b.
Next, change your loop to compute the sum of the ASCII codes of all the characters in a string. **|** ----- c.
Finally, modify your code again to return a new list that contains the ASCII codes of each character in the string. Does the expression map(ord, S) have a similar effect? (Hint: see Chapter 14.) 2.
Backslash characters.
What happens on your machine when you type the following code interactively? ``` for i in range(50): print('hello %d\n\a' % i) ``` Beware that if it’s run outside of the IDLE interface this example may beep at you, so you may not want to run it in a crowded lab.
IDLE prints odd characters instead of beeping (see the backslash escape characters in Table 7-2). 3. Sorting dictionaries. In Chapter 8, we saw that dictionaries are unordered collections.
Write a for loop that prints a dictionary’s items in sorted (ascending) order. (Hint: use the dictionary keys and list sort methods, or the newer sorted built-in function.) 4.
Program logic alternatives. Consider the following code, which uses a while loop and found flag to search a list of powers of 2 for the value of 2 raised to the fifth power (32).
It’s stored in a module file called power.py. ``` L = [1, 2, 4, 8, 16, 32, 64] X = 5 found = False i = 0 while not found and i < len(L): if 2 ** X == L[i]: found = True else: i = i+1 if found: print('at index', i) else: print(X, 'not found') C:\book\te...
Follow the steps outlined here to improve it (for all the transformations, you may either type your code interactively or store it in a script file run from the system command line—using a file makes this exercise much easier): a.
First, rewrite this code with a while loop else clause to eliminate the found flag and final if statement. b.
Next, rewrite the example to use a for loop with an else clause, to eliminate the explicit list-indexing logic.
(Hint: to get the index of an item, use the list ``` index method—L.index(X) returns the offset of the first X in list L.) ``` **|** ----- c.
Next, remove the loop completely by rewriting the example with a simple in operator membership expression. (See Chapter 8 for more details, or type this to test: 2 in [1,2,3].) d.
Finally, use a for loop and the list append method to generate the powers-of-2 list (L) instead of hardcoding a list literal. Deeper thoughts: e.
Do you think it would improve performance to move the 2 ** X expression outside the loops? How would you code that? f.
As we saw in exercise 1, Python includes a map(function, list) tool that can generate a powers-of-2 list, too: map(lambda x: 2 ** x, range(7)).
Try typing this code interactively; we’ll meet lambda more formally in Chapter 19. **|** ----- ##### PART IV ## Functions ----- ----- ###### CHAPTER 16 ### Function Basics In Part III, we looked at basic procedural statements in Python.
Here, we’ll move on to explore a set of additional statements that we can use to create functions of our own. In simple terms, a function is a device that groups a set of statements so they can be run more than once in a program.
Functions also can compute a result value and let us specify parameters that serve as function inputs, which may differ each time the code is run.
Coding an operation as a function makes it a generally useful tool, which we can use in a variety of contexts. More fundamentally, functions are the alternative to programming by cutting and pasting—rather than having multiple redundant copies of an operation’s code, we can factor it into a single function.
In so doing, we reduce our future work radically: if the operation must be changed later, we only have one copy to update, not many. Functions are the most basic program structure Python provides for maximizing code _reuse and minimizing code redundancy.
As we’ll see, functions are also a design tool_ that lets us split complex systems into manageable parts.
Table 16-1 summarizes the primary function-related tools we’ll study in this part of the book. _Table 16-1.
Function-related statements and expressions_ **Statement** **Examples** Calls `myfunc('spam', 'eggs', meat=ham)` ``` def, def adder(a, b=1, *c): return return a + b + c[0] global def changer(): global x; x = 'new' nonlocal def changer(): nonlocal x; x = 'new' yield def squares(x): for i...
Functions are a nearly universal program-structuring device. You may have come across them before in other languages, where they may have been called subrou_tines or procedures.
As a brief introduction, functions serve two primary development_ roles: _Maximizing code reuse and minimizing redundancy_ As in most programming languages, Python functions are the simplest way to package logic you may wish to use in more than one place and more than one time. Up until now, all the code we’ve been wr...
Functions allow us to group and generalize code to be used arbitrarily many times later.
Because they allow us to code an operation in a single place and use it in many places, Python functions are the most basic factoring tool in the language: they allow us to reduce code redundancy in our programs, and thereby reduce maintenance effort. _Procedural decomposition_ Functions also provide a tool for splitti...
For instance, to make a pizza from scratch, you would start by mixing the dough, rolling it out, adding toppings, baking it, and so on.
If you were programming a pizza-making robot, functions would help you divide the overall “make pizza” task into chunks—one function for each subtask in the process.
It’s easier to implement the smaller tasks in isolation than it is to implement the entire process at once.
In general, functions are about procedure—how to do something, rather than what you’re doing it to.
We’ll see why this distinction matters in Part VI, when we start making new object with classes. In this part of the book, we’ll explore the tools used to code functions in Python: function basics, scope rules, and argument passing, along with a few related concepts such as generators and functional tools.
Because its importance begins to become more apparent at this level of coding, we’ll also revisit the notion of polymorphism introduced earlier in the book.
As you’ll see, functions don’t imply much new syntax, but they do lead us to some bigger programming ideas. ###### Coding Functions Although it wasn’t made very formal, we’ve already used some functions in earlier chapters.
For instance, to make a file object, we called the built-in open function; similarly, we used the len built-in function to ask for the number of items in a collection object. In this chapter, we will explore how to write new functions in Python.
Functions we write behave the same way as the built-ins we’ve already seen: they are called in **|** ----- expressions, are passed values, and return results.
But writing new functions requires the application of a few additional ideas that haven’t yet been introduced.
Moreover, functions behave very differently in Python than they do in compiled languages like C. Here is a brief introduction to the main concepts behind Python functions, all of which we will study in this part of the book: - def **is executable code.
Python functions are written with a new statement, the** ``` def.
Unlike functions in compiled languages such as C, def is an executable state ``` ment—your function does not exist until Python reaches and runs the def.
In fact, it’s legal (and even occasionally useful) to nest def statements inside if statements, ``` while loops, and even other defs.
In typical operation, def statements are coded in ``` module files and are naturally run to generate functions when a module file is first imported. - def **creates an object and assigns it to a name.
When Python reaches and runs** a def statement, it generates a new function object and assigns it to the function’s name.
As with all assignments, the function name becomes a reference to the function object.
There’s nothing magic about the name of a function—as you’ll see, the function object can be assigned to other names, stored in a list, and so on. Function objects may also have arbitrary user-defined attributes attached to them to record data. - lambda **creates an object but returns it as a result.
Functions may also be created** with the lambda expression, a feature that allows us to in-line function definitions in places where a def statement won’t work syntactically (this is a more advanced concept that we’ll defer until Chapter 19). - return **sends a result object back to the caller.
When a function is called, the** caller stops until the function finishes its work and returns control to the caller. Functions that compute a value send it back to the caller with a return statement; the returned value becomes the result of the function call. - yield **sends a result object back to the caller, but r...
Functions known as generators may also use the yield statement to send back** a value and suspend their state such that they may be resumed later, to produce a series of results over time.
This is another advanced topic covered later in this part of the book. - global **declares module-level variables that are to be assigned.
By default, all** names assigned in a function are local to that function and exist only while the function runs.
To assign a name in the enclosing module, functions need to list it in a global statement.
More generally, names are always looked up in scopes— places where variables are stored—and assignments bind names to scopes. - nonlocal **declares enclosing function variables that are to be assigned.
Simi-** larly, the `nonlocal statement added in Python 3.0 allows a function to assign a` name that exists in the scope of a syntactically enclosing def statement.
This allows **|** ----- enclosing functions to serve as a place to retain state—information remembered when a function is called—without using shared global names. - Arguments are passed by assignment (object reference).
In Python, arguments are passed to functions by assignment (which, as we’ve learned, means by object reference).
As you’ll see, in Python’s model the caller and function share objects by references, but there is no name aliasing.
Changing an argument name within a function does not also change the corresponding name in the caller, but changing passed-in mutable objects can change objects shared by the caller. - Arguments, return values, and variables are not declared.
As with everything in Python, there are no type constraints on functions.
In fact, nothing about a function needs to be declared ahead of time: you can pass in arguments of any type, return any kind of object, and so on.
As one consequence, a single function can often be applied to a variety of object types—any objects that sport a compatible _interface (methods and expressions) will do, regardless of their specific types._ If some of the preceding words didn’t sink in, don’t worry—we’ll explore all of these concepts with real code in...
Let’s get started by expanding on some of these ideas and looking at a few examples. ###### def Statements The def statement creates a function object and assigns it to a name.
Its general format is as follows: ``` def <name>(arg1, arg2,...
argN): <statements> ``` As with all compound Python statements, def consists of a header line followed by a block of statements, usually indented (or a simple statement after the colon).
The statement block becomes the function’s body—that is, the code Python executes each time the function is called. The def header line specifies a function name that is assigned the function object, along with a list of zero or more arguments (sometimes called parameters) in parentheses. The argument names in the hea...
argN): ... return <value> ``` The Python return statement can show up anywhere in a function body; it ends the function call and sends a result back to the caller.
The return statement consists of an object expression that gives the function’s result.
The return statement is optional; if it’s not present, the function exits when the control flow falls off the end of the function **|** ----- body.
Technically, a function without a return statement returns the None object automatically, but this return value is usually ignored. Functions may also contain yield statements, which are designed to produce a series of values over time, but we’ll defer discussion of these until we survey generator topics in Chapter 20...
(Remember, all we have in Python is runtime; there is no such thing as a separate compile time.) Because it’s a statement, a def can appear anywhere a statement can—even nested in other statements.
For instance, although ``` defs normally are run when the module enclosing them is imported, it’s also completely ``` legal to nest a function `def inside an` `if statement to select between alternative` definitions: ``` if test: def func(): # Define func this way ... else: def func(): # Or...
Unlike in compiled languages such as C, Python functions do not need to be fully defined before the program runs.
More generally, ``` defs are not evaluated until they are reached and run, and the code inside defs is not ``` evaluated until the functions are later called. Because function definition happens at runtime, there’s nothing special about the function name.
What’s important is the object to which it refers: ``` othername = func # Assign function object othername() # Call func again ``` Here, the function was assigned to a different name and called through the new name. Like everything else in Python, functions are just objects; they are recorded explicitl...
In fact, besides calls, functions allow arbitrary _attributes to be attached to record information for later use:_ ``` def func(): ...
# Create function object func() # Call object func.attr = value # Attach attributes ``` **|** ----- ###### A First Example: Definitions and Calls Apart from such runtime concepts (which tend to seem most unique to programmers with backgrounds in traditional compiled languages), Python functions a...
Let’s code a first real example to demonstrate the basics.
As you’ll see, there are two sides to the function picture: a definition (the def that creates a function) and a call (an expression that tells Python to run the function’s body). ###### Definition Here’s a definition typed interactively that defines a function called times, which returns the product of its two argum...
return x * y` _# Body executed when called_ ``` ... ``` When Python reaches and runs this def, it creates a new function object that packages the function’s code and assigns the object to the name times.
Typically, such a statement is coded in a module file and runs when the enclosing file is imported; for something this small, though, the interactive prompt suffices. ###### Calls After the `def has run, you can call (run) the function in your program by adding` parentheses after the function’s name.
The parentheses may optionally contain one or more object arguments, to be passed (assigned) to the names in the function’s header: `>>> times(2, 4)` _# Arguments in parentheses_ ``` 8 ``` This expression passes two arguments to times.