OUTDATED, DO NOT USE: This tutorial was written in 1999 and was based on Python 1.5.2, which today is a really old version. I would not recommend using this tutorial to learn modern Python as the language has changed significantly. This page is left here in it's mostly-original form for historic reference only. Please consult the Python website for current documentation.

The def statement

  • Functions are defined with the def statement. The code for the function is indented under the def statement, and the name you give it becomes a reference to the code. Any value which is to be returned is given with the return statement.
    def factorial100():
       p = 1L
       for i in xrange(1,100):
          p = p * i
       return p
    
    print factorial100()  --> 933262...
    
  • Variables which are defined within a function a local and are not available outside the function (such as "p" and "i" above).
  • If control hits the end of the function code without a return statement, the function will return the special value None. This is similar to proceedures in some languages.

Function arguments

  • Functions can take arguments as expected
    def factorial( n ):
       p = 1L
       for i in xrange(1,n):
          p = p * i
       return p
    
    print factorial( 100 )  --> 933262...
    
  • Functions can have default parameter values
    def sum( last, first=1 ):
       s = 1L
       for i in xrange(first,last):
          s=s+i
       return s
    
    print 'Sum of numbers 1 to 100 is %d' % sum(100)
    print 'Sum of numbers 50 to 100 is %d' % sum(100,50)
    
  • Arguments can be called by name rather than position
    print 'Sum of numbers 50 to 100 is %d' % sum( first=50, last=100 )
    
  • Functions can accept a variable number of arguments by declaring the last known one with a "*" prefix. That variable will then be a tuple containing the rest of all the arguments with which the function was called.
    def func1( a, b, *c ):
       print a, b, c
    
    func1( 1, 2 )           --> 1 2 ()
    func1( 1, 2, 3 )        --> 1 2 (3,)
    func1( 1, 2, 3, 4 )     --> 1 2 (3,4)
    func1( 1, 2, 3, 4, 5 )  --> 1 2 (3,4,5)
    
  • Functions can also accept any number of arguments which are given by name, by using the "**" prefix. That variable will then be a dictionary of all the argument names and values.
    def func1( a, **d ):
       print a, d
    
    func1( 1 )                      --> 1 {}
    func1( 1, size=14 )             --> 1 { 'size':14 }
    func1( 1, width=60, height=12 ) --> 1 { 'height':12, 'width':60 }
    
  • You can also combine variable positional and named arguments together. Positional parameters are always filled in first.
    def func1( a, *b, **c ):
       print a, b, c
    
    func1( 1 )              --> 1 () {}
    func1( 1, 2, 3 )        --> 1 (2,3) {}
    func1( 1, x=20 )        --> 1 () {'x':2}
    func1( 1, 2, 3, x=20 )  --> 1 (2,3) {'x':20}