Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional Beginning Python - From Novice to Professional

16.01.2014 Views

CHAPTER 6 ■ ABSTRACTION 111 Creating Your Own Functions A function is something you can call (possibly with some parameters, the things you put in the parentheses), which performs an action and returns a value. In general, you can tell whether something is callable or not with the built-in function callable: >>> import math >>> x = 1 >>> y = math.sqrt >>> callable(x) 0 >>> callable(y) 1 As you know from the previous section, creating functions is central to structured programming. So how do you define a function? With the def (or “function definition”) statement: def hello(name): return 'Hello, ' + name + '!' After running this, you have a new function available, called hello, which returns a string with a greeting for the name given as the only parameter. You can use this function just like you used the built-in ones: >>> print hello('world') Hello, world! >>> print hello('Gumby') Hello, Gumby! Pretty neat, huh? Consider how you would write a function that returned a list of Fibonacci numbers. Easy! You just use the code from before, and instead of reading in a number from the user, you receive it as a parameter: def fibs(num): result = [0, 1] for i in range(num-2): result.append(result[-2] + result[-1]) return result After running this statement, you’ve basically told the interpreter how to calculate Fibonacci numbers—so now you don’t have to worry about the details anymore. You simply use the function fibs: >>> fibs(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] >>> fibs(15) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] The names num and result are quite arbitrary in this example, but return is important. The return statement is used to return something from the function (which is also how we used it in the preceding hello function).

112 CHAPTER 6 ■ ABSTRACTION ■Tip Your functions can return more than one value—simply collect them in a tuple and return that. Documenting Functions If you want to document your functions so that you’re certain that others will understand them later on, you can add comments (beginning with the hash sign, #). Another way of writing comments is simply to write strings by themselves. Such strings can be particularly useful in some places, such as right after a def statement (and at the beginning of a module or a class— you learn more about those later in the book). If you put a string at the beginning of a function, it is stored as part of the function and is called a docstring. The following code demonstrates how to add a docstring to a function: def square(x): 'Calculates the square of the number x.' return x*x The docstring may be accessed like this: >>> square.__doc__ 'Calculates the square of the number x.' ■Note __doc__ is a function attribute. You’ll learn a lot more about attributes in Chapter 7. The double underscores in the attribute name mean that this is a special attribute. Special or “magic” attributes like this are discussed in Chapter 9. There is a built-in function called help, which can be quite useful. If you use it in the interactive interpreter, you can get information about a function, including its docstring: >>> help(square) Help on function square in module __main__: square(x) Calculates the square of the number x. You meet the help function again in Chapter 10. Functions That Aren’t Really Functions Functions, in the mathematical sense, always return something that is calculated from their parameters. In Python, some functions don’t return anything. In other languages (such as Pascal), such functions may be called other things (such as procedures), but in Python a function is a function, even if it technically isn’t. Functions that don’t return anything simply don’t have a return statement. Or, if they do have return statements, there is no value after the word return:

CHAPTER 6 ■ ABSTRACTION 111<br />

Creating Your Own Functions<br />

A function is something you can call (possibly with some parameters, the things you put in the<br />

parentheses), which performs an action and returns a value. In general, you can tell whether<br />

something is callable or not with the built-in function callable:<br />

>>> import math<br />

>>> x = 1<br />

>>> y = math.sqrt<br />

>>> callable(x)<br />

0<br />

>>> callable(y)<br />

1<br />

As you know from the previous section, creating functions is central <strong>to</strong> structured programming.<br />

So how do you define a function? With the def (or “function definition”) statement:<br />

def hello(name):<br />

return 'Hello, ' + name + '!'<br />

After running this, you have a new function available, called hello, which returns a string<br />

with a greeting for the name given as the only parameter. You can use this function just like you<br />

used the built-in ones:<br />

>>> print hello('world')<br />

Hello, world!<br />

>>> print hello('Gumby')<br />

Hello, Gumby!<br />

Pretty neat, huh? Consider how you would write a function that returned a list of Fibonacci<br />

numbers. Easy! You just use the code from before, and instead of reading in a number from the<br />

user, you receive it as a parameter:<br />

def fibs(num):<br />

result = [0, 1]<br />

for i in range(num-2):<br />

result.append(result[-2] + result[-1])<br />

return result<br />

After running this statement, you’ve basically <strong>to</strong>ld the interpreter how <strong>to</strong> calculate<br />

Fibonacci numbers—so now you don’t have <strong>to</strong> worry about the details anymore. You simply<br />

use the function fibs:<br />

>>> fibs(10)<br />

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]<br />

>>> fibs(15)<br />

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]<br />

The names num and result are quite arbitrary in this example, but return is important. The<br />

return statement is used <strong>to</strong> return something from the function (which is also how we used it<br />

in the preceding hello function).

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

Saved successfully!

Ooh no, something went wrong!