← 学习库 Think Python 2e 目录

Chapter 4

> 来源: Think Python 2e (Allen B. Downey)

> 原页: https://greenteapress.com/thinkpython/html/thinkpython004.html

\

[插图缺失:thinkpython003.html]
[ [](thinkpython005.html)

------------------------------------------------------------------------

Chapter 3   Functions

3.1   Function calls

In the context of programming, a function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can “call” the function by name. We have already seen one example of a function call:

>>> type(32)

<type 'int'>

The name of the function is type. The expression in parentheses is called the argument of the function. The result, for this function, is the type of the argument.

It is common to say that a function “takes” an argument and “returns” a result. The result is called the return value.

3.2   Type conversion functions

Python provides built-in functions that convert values from one type to another. The int function takes any value and converts it to an integer, if it can, or complains otherwise:

type00008

int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part:

type00010

type0 converts integers and strings to floating-point numbers:

type00012

Finally, int converts its argument to a string:

type00014

3.3   Math functions

Python has a math module that provides most of the familiar mathematical functions. A module is a file that contains a collection of related functions.

Before we can use the module, we have to import it:

type00015

This statement creates a module object named math. If you print the module object, you get some information about it:

type00016

The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation.

type00017

The first example uses type0 to compute a signal-to-noise ratio in decibels (assuming that type00019 and type00020 are defined). The math module also provides int, which computes logarithms base e.

The second example finds the sine of type000. The name of the variable is a hint that int and the other trigonometric functions (int, int, etc.) take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2 π:

type00027

The expression type000 gets the variable e0 from the math module. The value of this variable is an approximation of π, accurate to about 15 digits.

If you know your trigonometry, you can check the previous result by comparing it to the square root of two divided by two:

type00030

3.4   Composition

So far, we have looked at the elements of a program—variables, expressions, and statements—in isolation, without talking about how to combine them.

One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, the argument of a function can be any kind of expression, including arithmetic operators:

type00031

And even function calls:

type00032

Almost anywhere you can put a value, you can put an arbitrary expression, with one exception: the left side of an assignment statement has to be a variable name. Any other expression on the left side is a syntax error (we will see exceptions to this rule later).

type00033

3.5   Adding new functions

So far, we have only been using the functions that come with Python, but it is also possible to add new functions. A function definition specifies the name of a new function and the sequence of statements that execute when the function is called.

Here is an example:

type00034

int is a keyword that indicates that this is a function definition. The name of the function is type00036. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.

The empty parentheses after the name indicate that this function doesn’t take any arguments.

The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, the indentation is always four spaces (see Section 3.14). The body can contain any number of statements.

The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote (which is also an apostrophe) appears in the string.

If you type a function definition in interactive mode, the interpreter prints ellipses (...) to let you know that the definition isn’t complete:

type00037

To end the function, you have to enter an empty line (this is not necessary in a script).

Defining a function creates a variable with the same name.

type00038

The value of type00039 is a function object, which has type type00040.

The syntax for calling the new function is the same as for built-in functions:

type00041

Once you have defined a function, you can use it inside another function. For example, to repeat the previous refrain, we could write a function called type00042:

type00043

And then call type00044:

type00045

But that’s not really how the song goes.

3.6   Definitions and uses

Pulling together the code fragments from the previous section, the whole program looks like this:

type00046

This program contains two function definitions: type00047 and type00048. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not get executed until the function is called, and the function definition generates no output.

As you might expect, you have to create a function before you can execute it. In other words, the function definition has to be executed before the first time it is called.

Exercise 1  

Move the last line of this program to the top, so the function call appears before the definitions. Run the program and see what error message you get.

Exercise 2  

Move the function call back to the bottom and move the definition of type00049 after the definition of type00050. What happens when you run this program?

3.7   Flow of execution

In order to ensure that a function is defined before its first use, you have to know the order in which statements are executed, which is called the flow of execution.

Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom.

Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called.

A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, executes all the statements there, and then comes back to pick up where it left off.

That sounds simple enough, until you remember that one function can call another. While in the middle of one function, the program might have to execute the statements in another function. But while executing that new function, the program might have to execute yet another function!

Fortunately, Python is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it. When it gets to the end of the program, it terminates.

What’s the moral of this sordid tale? When you read a program, you don’t always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution.

3.8   Parameters and arguments

Some of the built-in functions we have seen require arguments. For example, when you call type0005 you pass a number as an argument. Some functions take more than one argument: type0005 takes two, the base and the exponent.

Inside the function, the arguments are assigned to variables called parameters. Here is an example of a user-defined function that takes an argument:

type00053

This function assigns the argument to a parameter named type0. When the function is called, it prints the value of the parameter (whatever it is) twice.

This function works with any value that can be printed.

type00055

The same rules of composition that apply to built-in functions also apply to user-defined functions, so we can use any kind of expression as an argument for type00056:

type00057

The argument is evaluated before the function is called, so in the examples the expressions type00058 and type00059 are only evaluated once.

You can also use a variable as an argument:

type00060

The name of the variable we pass as an argument (type000) has nothing to do with the name of the parameter (type0). It doesn’t matter what the value was called back home (in the caller); here in type00063, we call everybody type0.

3.9   Variables and parameters are local

When you create a variable inside a function, it is local, which means that it only exists inside the function. For example:

type00065

This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it:

type00066

When type00067 terminates, the variable int is destroyed. If we try to print it, we get an exception:

type00069

Parameters are also local. For example, outside type00070, there is no such thing as type0.

3.10   Stack diagrams

To keep track of which variables can be used where, it is sometimes useful to draw a stack diagram. Like state diagrams, stack diagrams show the value of each variable, but they also show the function each variable belongs to.

Each function is represented by a frame. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it. The stack diagram for the previous example is shown in Figure 3.1.


[插图缺失:thinkpython004.png]

Figure 3.1: Stack diagram.


The frames are arranged in a stack that indicates which function called which, and so on. In this example, type00072 was called by type00073, and type00074 was called by type0007, which is a special name for the topmost frame. When you create a variable outside of any function, it belongs to type0007.

Each parameter refers to the same value as its corresponding argument. So, type0 has the same value as type0, type0 has the same value as type0, and type0 has the same value as int.

If an error occurs during a function call, Python prints the name of the function, and the name of the function that called it, and the name of the function that called that, all the way back to type0008.

For example, if you try to access int from within type00085, you get a type00086:

type00087

This list of functions is called a traceback. It tells you what program file the error occurred in, and what line, and what functions were executing at the time. It also shows the line of code that caused the error.

The order of the functions in the traceback is the same as the order of the frames in the stack diagram. The function that is currently running is at the bottom.

3.11   Fruitful functions and void functions

Some of the functions we are using, such as the math functions, yield results; for lack of a better name, I call them fruitful functions. Other functions, like type00088, perform an action but don’t return a value. They are called void functions.

When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression:

type00089

When you call a function in interactive mode, Python displays the result:

type00090

But in a script, if you call a fruitful function all by itself, the return value is lost forever!

type00091

This script computes the square root of 5, but since it doesn’t store or display the result, it is not very useful.

Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the result to a variable, you get a special value called type.

type00093

The value type is not the same as the string type00. It is a special value that has its own type:

type00096

The functions we have written so far are all void. We will start writing fruitful functions in a few chapters.

3.12   Why functions?

It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:

3.13   Importing with type

Python provides two ways to import modules; we have already seen one:

type00098

If you import type, you get a module object named type. The module object contains constants like e0 and functions like int and int.

But if you try to access e0 directly, you get an error.

type00105

As an alternative, you can import an object from a module like this:

type00106

Now you can access e0 directly, without dot notation.

type00108

Or you can use the star operator to import everything from the module:

type00109

The advantage of importing everything from the math module is that your code can be more concise. The disadvantage is that there might be conflicts between names defined in different modules, or between a name from a module and one of your variables.

3.14   Debugging

If you are using a text editor to write your scripts, you might run into problems with spaces and tabs. The best way to avoid these problems is to use spaces exclusively (no tabs). Most text editors that know about Python do this by default, but some don’t.

Tabs and spaces are usually invisible, which makes them hard to debug, so try to find an editor that manages indentation for you.

Also, don’t forget to save your program before you run it. Some development environments do this automatically, but some don’t. In that case the program you are looking at in the text editor is not the same as the program you are running.

Debugging can take a long time if you keep running the same, incorrect, program over and over!

Make sure that the code you are looking at is the code you are running. If you’re not sure, put something like type00110 at the beginning of the program and run it again. If you don’t see type0, you’re not running the right program!

3.15   Glossary

function:

A named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result.

function definition:

A statement that creates a new function, specifying its name, parameters, and the statements it executes.

function object:

A value created by a function definition. The name of the function is a variable that refers to a function object.

header:

The first line of a function definition.

body:

The sequence of statements inside a function definition.

parameter:

A name used inside a function to refer to the value passed as an argument.

function call:

A statement that executes a function. It consists of the function name followed by an argument list.

argument:

A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.

local variable:

A variable defined inside a function. A local variable can only be used inside its function.

return value:

The result of a function. If a function call is used as an expression, the return value is the value of the expression.

fruitful function:

A function that returns a value.

void function:

A function that doesn’t return a value.

module:

A file that contains a collection of related functions and other definitions.

import statement:

A statement that reads a module file and creates a module object.

module object:

A value created by an type00 statement that provides access to the values defined in a module.

dot notation:

The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.

composition:

Using an expression as part of a larger expression, or a statement as part of a larger statement.

flow of execution:

The order in which statements are executed during a program run.

stack diagram:

A graphical representation of a stack of functions, their variables, and the values they refer to.

frame:

A box in a stack diagram that represents a function call. It contains the local variables and parameters of the function.

traceback:

A list of the functions that are executing, printed when an exception occurs.

3.16   Exercises

Exercise 3  

Python provides a built-in function called int that returns the length of a string, so the value of type00114 is 5.

Write a function named type00115 that takes a string named e as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.

type00117

Exercise 4  

A function object is a value you can assign to a variable or pass as an argument. For example, type0011 is a function that takes a function object as an argument and calls it twice:

type00119

Here’s an example that uses type0012 to call a function named type00121 twice.

type00122

  1. Type this example into a script and test it.
  2. Modify type0012 so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
  3. Write a more general version of type00124, called type00125, that takes a string as a parameter and prints it twice.
  4. Use the modified version of type0012 to call type00127 twice, passing type00 as an argument.
  5. Define a new function called type001 that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.

Solution: type00130.

Exercise 5  

This exercise can be done using only the statements and other features we have learned so far.

  1. Write a function that draws a grid like the following:

    type00131

    Hint: to print more than one value on a line, you can print a comma-separated sequence:

    type00132

    If the sequence ends with a comma, Python leaves the line unfinished, so the value printed next appears on the same line.

    type00133

    The output of these statements is type0.

    A type0 statement all by itself ends the current line and goes to the next line.

  2. Write a function that draws a similar grid with four rows and four columns.

Solution: type00136. Credit: This exercise is based on an exercise in Oualline, Practical C Programming, Third Edition, O’Reilly Media, 1997.

Contribute

If you would like to make a contribution to support my books, you can use the button below. Thank you!

Pay what you want:

Small $1.00 USD Medium $5.00 USD Large $10.00 USD X-Large $20.00 USD XX-Large $50.00 USD

Are you using one of our books in a class?

We'd like to know about it. Please consider filling out this short survey.


------------------------------------------------------------------------

\

[插图缺失:thinkpython003.html]
[ [](thinkpython005.html)

---

← Chapter 3Chapter 5 →