Python - (def|define) function (procedure)


def function are one type of function declaration. See Python - (Function|Procedure|definition).

Functions (called also procedure) are defined using the keyword def that stands for define


# Function definition
def myFunction(parameter1, parameter2):
    ''' This a docstring who describe what the function does'''
    # This is the body where you do something 
    return aVariable

# Calling the function
myFunction(argument1, argument2)


  • the argument is the calling variable of the function,
  • the parameter is the variable of the function definition.

When the procedure is invoked, the formal argument (the variable) is temporarily bound to the actual argument, and the body of the procedure is executed. At the end, the binding of the actual argument is removed. (The binding was temporary.)

def generates a function and assigns it to a name.


Python - Data Type

def addS(x):
    return x + 's'
print type(addS)
print addS
<type 'function'>
<function addS at 0xb0ef95dc>

Splat arguments

Splat arguments are an arbitrary number of arguments.

  • String
def favorite_actors(*actor):
    """Prints out your favorite actorS (plural!)"""
    print "Your favorite actors are:" , actor

favorite_actors("Michael Palin", "John Cleese", "Graham Chapman")
Your favorite actors are: (u'Michael Palin', u'John Cleese', u'Graham Chapman')
  • Number
def biggest_number(*args):
    print max(args)

biggest_number(-10, -5, 5, 10)

built-in functions

Built-in functions are function that doesn't need an import statement.


>>> help(randint)
Help on method randint in module random:

randint(self, a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.

Documentation / Reference

Powered by ComboStrap