04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

112 CHAPTER 6 ■ ABSTRACTION<br />

■Tip Your functions can return more than one value—simply collect them in a tuple and return that.<br />

Documenting Functions<br />

If you want to document your functions so that you’re certain that others will understand them<br />

later on, you can add comments (beginning with the hash sign, #). Another way of writing<br />

comments is simply to write strings by themselves. Such strings can be particularly useful in<br />

some places, such as right after a def statement (and at the beginning of a module or a class—<br />

you learn more about those later in the book). If you put a string at the beginning of a function,<br />

it is stored as part of the function and is called a docstring. The following code demonstrates<br />

how to add a docstring to a function:<br />

def square(x):<br />

'Calculates the square of the number x.'<br />

return x*x<br />

The docstring may be accessed like this:<br />

>>> square.__doc__<br />

'Calculates the square of the number x.'<br />

■Note __doc__ is a function attribute. You’ll learn a lot more about attributes in Chapter 7. The double<br />

underscores in the attribute name mean that this is a special attribute. Special or “magic” attributes like this<br />

are discussed in Chapter 9.<br />

There is a built-in function called help, which can be quite useful. If you use it in the interactive<br />

interpreter, you can get information about a function, including its docstring:<br />

>>> help(square)<br />

Help on function square in module __main__:<br />

square(x)<br />

Calculates the square of the number x.<br />

You meet the help function again in Chapter 10.<br />

Functions That Aren’t Really Functions<br />

Functions, in the mathematical sense, always return something that is calculated from their<br />

parameters. In Python, some functions don’t return anything. In other languages (such as Pascal),<br />

such functions may be called other things (such as procedures), but in Python a function is a<br />

function, even if it technically isn’t. Functions that don’t return anything simply don’t have a<br />

return statement. Or, if they do have return statements, there is no value after the word return:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!