Python - (def|define) function (procedure)

Card Puncher Data Processing

Python - (def|define) function (procedure)

About

def function are one type of function declaration. See Function.

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

Syntax

# 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)

where:

  • 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.

Type

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)
10

built-in functions

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

Help

>>> 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





Discover More
Card Puncher Data Processing
Python - lambda functions

in Python. See The expression below yields a function object. The unnamed object behaves like a function object defined with lambda generates a function and returns it, while def generates a...
Card Puncher Data Processing
Python Package - Import

import functionality in Python In order to use the names (generally, variable and function definitions) defined in a module, you must either: import the module itself or import the specific definitions,...



Share this page:
Follow us:
Task Runner