11.3. Creating Functions

11.3.1. def Statement

Functions are created using the def statement, with a syntax like the following:

							def
							function_name(arguments):
    "function_documentation_string"
    function_body_suite
						

The header line consists of the def keyword, the function name, and a set of arguments (if any). The remainder of the def clause consists of an optional but highly-recommended documentation string and the required function body suite. We have seen many function declarations throughout this text, and here is another:

							def helloSomeone(who):
    'returns a salutory string customized with the input'
    return "Hello" + str(who)

11.3.2. Declaration vs. Definition

Some programming languages differentiate between function declarations and function definitions. A function declaration consists of providing the parser with the function name, and the names (and traditionally the types) of its arguments, without necessarily giving any lines of code for the function, which is usually referred to as the function definition.

In languages where there is a distinction, it is usually because the function definition may belong in a physically different location in the code from the function declaration. Python does not make a distinction between the two, as a function clause is made up of a declarative header line which is immediately followed by its defining suite.

11.3.3. Forward References

Like some other high-level languages, Python does not permit you to reference or call a function before it has been declared. We can try a few examples to illustrate this:

							def foo():
    print 'in foo()'
    bar()

If we were to call foo() here, it will fail because bar() has not been declared yet:

>>> foo()
in foo()
Traceback (innermost last):
  File "<stdin>", line 1, in ? 
  File "<stdin>", line 3, in foo
NameError: bar

We will now define bar(), placing its declaration before foo()'s declaration:

							def bar():
    print 'in bar()'

def foo():
    print 'in foo()'
    bar()

Now we can safely call foo() with no problems:

>>> foo()
in foo()
in bar()

In fact, we can even declare foo() before bar():

							def foo():
    print 'in foo()'
    bar()

def bar():
    print 'in bar()'

Amazingly enough, this code still works fine with no forward referencing problems:

>>> foo()
in foo()
in bar()

This piece of code is fine because even though a call to bar() (from foo()) appears before bar()'s definition, foo() itself is not called before bar() is declared. In other words, we declared foo(), then bar(), and then called foo(), but by that time, bar() existed already, so the call succeeds.

Notice that the output of foo() succeeded before the error came about. NameError is the exception that is always raised when any uninitialized identifiers are accessed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset