PySchools Python Quick Reference Guide

Functions

«  Variables and Data Types   ::   Contents   ::   Conditionals  »

Functions

Function is commonly used to group a series of statements together to achieve a specific objective.

To declare a function:

def add_one(x):
    '''
    This function takes in a number as argument and increment the number by 1
    '''
    print x + 1

To invoke a function:

>>> add_one(5)
6
>>> add_one(2)
3

Functions with return statement

By default, all functions return None. Function that returns value is known as fruitful function.

def add_one(x):
    '''
    This function takes in a number as argument and increment the number by 1
    '''
    return x + 1

It is a good practice to assign the value returned by a function to a variable.

>>> x = add_one(5)
>>> print x
6

Using built-in functions

The python installation is pre-packaged with many modules which contain some commonly used functions. One such module is the math module. To use a builtin module, you have to use the import statement.

>>> import math
>>> math.sqrt(4.0)              # Note: need to include the module name in the function call
2
>>> import random
>>> random.randint(0, 100)
>>> 20

The Anonymous functions

The lambda keyword can be used to create small anonymous functions. An example of using lambda keyword is shown below:

>>> total = lambda num1, num2: num1 + num2      #LHS of colon : arguments, # RHS of colon: function body
>>> total(1,2)
3

See also

Ready for some practice? Test your understanding at PySchools: Functions.

«  Variables and Data Types   ::   Contents   ::   Conditionals  »