Introduction to Python: Class 3

Page Contents


Functions are one of the callable types in Python. There is no real distinction between functions and procedures as in some languages: all functions return a value. However, if you don't explicitly terminate a function via the return statement, the value returned is None.

Python functions are first-class values, and hence can be stored in data structures, passed as parameters to other functions, and returned as the value of other functions.


The syntax of a function definition is:

      def name(parameter list):

Here is the simplest Python function definition:

      def f(): pass

This defines f as a function that returns None because execution falls off the end of the function, or if your prefer, because no return statement is executed. Here are some more trivial function definitions (note the documentation strings"):

      def f():
          "returns None explicitly"
          return None
      def httpheaders():
          "return a list of HTTP protocol header strings"
	  return ["Content-Type: text/html", "Server: myHTPP/1.0"]

A function definition can appear anywhere that a statement can appear, including inside other functions. The definition binds name to the function object.

Parameter Lists

Python supports rich parameter lists, with such features as positional parameters, keyword parameter, defaults, and optional parameter.