Linux/Unix > Python Essential Reference, Second Edition > 1. A Tutorial Introduction > Functions | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137110162165015143224220233

### Functions

You use the `def` statement to create a function, as shown in the following example:

    def remainder(a,b):
            q = a/b
            r = a - q*b
            return r

To invoke a function, simply use the name of the function followed by its arguments enclosed in parentheses, such as `result = remainder(37,15)`. You can use a tuple to return multiple values from a function, as in the following example:

    def divide(a,b):
            q = a/b        # If a and b are integers, q is an integer
            r = a - q*b
            return (q,r)

When returning multiple values in a tuple, it’s often useful to invoke the function as follows:

    quotient, remainder = divide(1456,33)

To assign a default value to a parameter, use assignment:

    def connect(hostname,port,timeout=300):
          # Function body

When default values are given in a function definition, they can be omitted from subsequent function calls. For example:

    connect('www.python.org', 80)

You also can invoke functions by using keyword arguments and supplying the arguments in arbitrary order. For example:

    connect(port=80,hostname="www.python.org")

When variables are created or assigned inside a function, their scope is local. To modify the value of a global variable from inside a function, use the `global` statement as follows:

    a = 4.5
    ...
    def foo():
            global a
            a = 8.8             # Changes the global variable a

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.