You can access the docstring of a function by refering to the __doc__
attribute, or by passing the name of the function to the help function
when running python interactively. In addition, some python-aware editors will
display the docstring as a tool tip when you move your cursor over the function's name
in your program.
Here's a illustration of a function; the function merge combines two lists, adding items from the second list only if they do not appear in the first.
def merge(list1,list2): '''merge(list1,list2) returns a list consisting of the original list1 along with any elements of list2 which were not already in list 1''' newlist = list1[:] for i in list2: if i not in newlist: newlist.append(i) return newlistNotice that, inside the function, newlist was created from list1 using the techniques discussed in Section 6.1, so that the first list passed to merge would not be modified by the function. The return statement is required, since the goal of the function is to provide a new list which combines the elements of the two lists passed to the function.
To call a function, you refer to its name with a parenthesized list of arguments; if the function takes no arguments, you follow the function name with a set of empty parentheses, so that Python won't confuse the function call with a reference to an ordinary variable. Arguments to functions behave much the way that assignments do (See Section 6.1): modifying a scalar or immutable object which has been passed through the argument list of a function will not modify the object itself, but modifying the elements of a mutable object (like a list or dictionary) passed to a function will actually change those elements in the calling environment. The following program shows how the merge function could be called. For now, we'll assume that the definition of was typed in interactively before the example, or, if the program was in a file, the function definition appeared earlier in the same file as the example. Later we'll see how you can use the import statement to access function definitions from other files, without repeatedly entering the function definition.
>>> one = [7,12,19,44,32] >>> two = [8,12,19,31,44,66] >>> print merge(one,two) [7, 12, 19, 44, 32, 8, 31, 66] >>> print one [7, 12, 19, 44, 32]