Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


WDVL Newsletter

jobs.webdeveloper.com

e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Programming in Python 3: A Complete Introduction to the Python Language

March 06, 2009

This week we'll cover the 4 kinds of functions that can be created in Python.

Excerpted from Programming in Python 3: A Complete Introduction to the Python Language by Mark Summerfield. ISBN: 0137129297, Copyright 2009. Used with the permission of Addison-Wesley Professional.

Custom Functions

Functions are a means by which we can package up and parameterize functionality. Four kinds of functions can be created in Python: global functions, local functions, lambda functions, and methods.

Every function we have created so far has been a global function. Global objects (including functions) are accessible to any code in the same module (i.e., the same .py file) in which the object is created. Global objects can also be accessed from other modules, as we will see in the next chapter.

Local functions (also called nested functions) are functions that are defined inside other functions. These functions are visible only to the function where they are defined; they are especially useful for creating small helper functions that have no use elsewhere. We first show them in Chapter 7.

Lambda functions are expressions, so they can be created at their point of use; however, they are much more limited than normal functions.

Methods are functions that are associated with a particular data type and can be used only in conjunction with the data type—they are introduced in Chapter 6 when we cover object- oriented programming.

Python provides many built-in functions, and the standard library and third-party libraries add hundreds more (thousands if we count all the methods), so in many cases the function we want has already been written. For this reason, it is always worth checking Python’s online documentation to see what is already available. See the "Online Documentation" sidebar.

The general syntax for creating a (global or local) function is: 

def functionName(parameters):
    suite

The parameters are optional ,and if there is more than one they are written as a sequence of comma-separated identifiers, or as a sequence of identifier=value pairs as we will discuss shortly. For example, here is a function that calculates the area of a triangle using Heron’s formula:

def heron(a, b, c):
   s = (a + b + c) / 2
   return math.sqrt(s * (s -a) * (s -b) * (s -c))

Inside the function, each parameter, a, b, and c, is initialized with the corresponding value that was passed as an argument. When the function is called, we must supply all of the arguments, for example, heron(3, 4, 5). If we give too few or too many arguments, a TypeError exception will be raised. When we do a call like this we are said to be using positional arguments, because each argument passed is set as the value of the parameter in the corresponding position. So in this case, a isset to3, b to 4, and c to 5, when the function is called.

Every function in Python returns a value, although it is perfectly acceptable (and common) to ignore the return value. The return value is either a single value or a tuple of values, and the values returned can be collections, so there are no practical limitations on what we can return. We can leave a function at any point by using the return statement. If we use return with no arguments, or if we don’t have a return statement at all, the function will return None. (In Chapter 6 we will cover the yield statement which can be used instead of return in certain kinds of functions.)

Some functions have parameters for which there can be a sensible default. For example, here is a function that counts the letters in a string, defaulting to the ASCII letters:

def letter_count(text, letters=string.ascii_letters):
    letters = frozenset(letters)
    count = 0
    for char in text:
        if char in letters:
            count += 1
    return count

We have specified a default value for the letters parameter by using the parameter=default syntax. This allows us to call letter_count() with just one argument, for example, letter_count("Maggie and Hopey"). Here, inside the function, letters will be the string that was given as the default value. But we can still change the default, for example, using an extra positional argument, letter_count("Maggie and Hopey", "aeiouAEIOU"), or using a keyword argument (covered next), letter_count("Maggie and Hopey", letters="aeiouAEIOU").

The parameter syntax does not permit us to follow parameters with default values with parameters that don’t have defaults, so def bad(a, b=1, c): won’t work. On the other hand, we are not forced to pass our arguments in the order they appear in the function’s definition—instead, we can use keyword arguments, passing each argument in the form name=value.

Custom Exceptions
Control Structures
Custom Functions Cont. - Page 2


Up to => Home / Authoring / Tutorials




Jupiter Online Media: internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and Jupiter Online Media

Jupitermedia Corporate Info


Legal Notices, Licensing, & Permissions, Privacy Policy.

Web Hosting | Newsletters | Tech Jobs | Shopping | E-mail Offers