Home      |       Contents       |       About

Prev: -       |       Next: Arguments

Functions defined

What is a function?

  • In general, a function is a named block of code that performs a specific task. Using its name a function can be "called" from another piece of code and executed during runtime.
  • Bidirectional communication between the calling part of code and the function is possible usually by passing parameter values (arguments) to the function and getting back the function output values.
  • The major benefits of using functions is code modularity and reusability. In other words, we assign specific tasks to smaller pieces of code (functions) to be called whenever and wherever needed in our main program.

Function 'def'

  • In Python a function is defined as follows:
In [ ]:
def func_name(list of parameters):
    block of statements
    return output_variables
  • Thus, to define a function:
    1. def: write the reserved name 'def' (from 'define') to start a function
    2. name and parameters: write the name of the function followed by a list of parameters (optional) in parantheses (obligatory); remember to put ':' at the end of the header
    3. docstring: not necessary but very helpful. Write here a short explanatory comment about function operation, inputs and outputs. You can easily retrieve it later to include it in your documentation
    4. function body: write the block of statements to be executed whan the function is called - indented!
    5. return: write the reserved work 'return' to denote the end of the function (optional: if 'return' is omitted the interpreter silently adds the 'return None' line)
    6. output values: if you want the function to return one or more values write them separated by comma right after the 'return' keyword
  • To call a function most often we:
    1. Write its name and a list of arguments. Arguments are the values we assign to parameters (or 'values we pass to the function'):
    2. or, Write an assignment with function at the right part:
             asum = func_name(arguments)

Function examples

In [3]:
def hello():                   # no need to always include parameters 
    print('Hello function!')   # remember indentation! 
                               # 'return None' is silently added by the interpreter 

hello()                        # calling the function by its name
Hello function!
  • In the example below, the function ask_name() is called inside a print() function. Generally, functions can be called wherever a variable name can also appear.
  • See also, how the help() function is called to present the function docstring
In [4]:
def ask_name():
    Gets and returns the user name from keyboard
    name = input('Please enter your name: ')
    return name

Help on function ask_name in module __main__:

    Gets and returns the user name from keyboard

Please enter your name: Nik
  • addcon() function below, accepts a and b as arguments from the main program and returns value c
In [6]:
def addcon(x,y):  
    Input: two numeric arguments -> returns their sum 
    Input: two string arguments -> returns their concatenation 
    return x+y                 

a = '7'
b = 'R'
c = addcon(a,b)                                   
  • stat() function below, accepts a list of numbers as argument and returns the mean and the standard deviation of the sample. Note that stat() returns a two-item tuple unpacked on mean and std names
  • There is a more elegant and efficient way of writing this print function that we shall see in the next section.
In [7]:
import random, math

def stat(numlist):
    Input: list of numerics
    Output: Mean and Standard deviation
    mn = sum(numlist)/len(numlist)
    sm = 0
    for k in numlist:
        sm += pow((k-mn), 2)
    sd = math.sqrt(sm/(len(numlist)-1))
    return mn, sd

mylist = [random.randint(1,100) for i in range(100)]
mean, std = stat(mylist)
print('Mean: {:5.2f}, Standard deviation: {:5.2f}'.format(mean, std))
Help on function stat in module __main__:

    Input: list of numerics
    Output: Mean and Standard deviation

Mean: 55.13, Standard deviation: 26.40

'def' is a command (not a 'declaration')

  • 'def' is an executable command (Python does not have but very few declarations) and as such it can be placed whenever needed in the program (not necessarily in the beginning of the code as it is typical for other languages)
  • Below is an example: the trans() function accepts 'oldstr' string as input and 'mode' as a flag, then defines the appropriate form of change() and outputs a new string by transforming the old string from low to caps or vice versa.
In [8]:
def trans(oldstr, mode):
    Changes the letter case of the input string - Returns a new string
    Input: string and mode (flag: 1-> returns UPPER case, all other -> returns lower case)
    if mode:
        def change(char):
            Alters the letetr case (upper or lower)  
            return char.upper()
        def change(char):
            Alters the letetr case (upper or lower)  
            return char.lower()
    for ch in oldstr:
        new_str += change(ch)
    return new_str

while True:
    txt = input('Text to transform: ')
    md = input('Enter: (1) From lower to Upper, or any other key (from Upper to lower)')
    print(trans(txt, md))
    if input('Enter for another run  /  "q" to quit') == 'q':
Text to transform: TEXT
Enter: (1) From lower to Upper, or any other key (from Upper to lower)
Enter for another run  /  "q" to quitq

How does Python execute a function?

Three major processes take place:
1. When the interpreter meets a 'def' command it constructs a new 'function' object in memory and adds a new binding in the namespace: the one between the name of the function and the 'function' object.
2. When the function is called, arguments pass to the local namespace of the function by shared object reference
3. After the execution of the function is over, a new object has been constructed (the one that the function returns) and is available in the namespace.

See the following example and visualization

In [8]:
def addcon(x,y):  
    Input: two numeric arguments -> returns their sum 
    Input: two string arguments -> returns their concatenation 
    return x+y                 

a = 5
b = 10
c = addcon(a,b)                                   
  • Left panel in figure below:
    • The 'function' object addcon(x,y) is constructed and referenced by the name 'addcon' (red arrow)
    • When called: arguments pass to the function by 'object reference' (that means: argument objects 5 and 10 are referenced both by parameters a, b in main program and x, y in the function)
  • Right panel:
    • After function execution an integer object with value 15 has been constructed and returned. It is referenced in the namespace by the name 'c' (red arrow)

  • Two more examples
In [2]:
import random

def sumpow(funclist, ex):
    Returns the sum of all funclist members raised to power ex  
    sm = 0
    for item in funclist:
        sm += item**ex
    return sm

alist = [random.randint(1,100) for x in range(10)] 
sum_squares = sumpow(alist, 2)
print(sum_squares, type(sum_squares))

# An integer object is constructed and returned by sumpow() 
# and a binding is added in the namespace between sum_squares and this integer object  
45262 <class 'int'>
In [7]:
import math 

def circle(r):
    Given the radius r it returns the circumference (c) and area (a) of a circle
    c = 2*math.pi*r
    a = math.pi*r**2
    return c, a

radius = 1
circumf, area = circle(radius)
print(circle(radius), type(circle(radius)))

# A tuple object (with 2 items) is constructed by circle() function and returned
# When a function returns more than one object, they are all packed in a tuple object container 
(6.283185307179586, 3.141592653589793) <class 'tuple'>

. Free learning material
. See full copyright and disclaimer notice