Functions in Python

One of the many ways to structure the logic of your program is the use of functions.

There are two common reasons to use functions. The first one is that it makes code reusable. The second is that functions increase the modularity of your code; instead of long stretches of code you cut the code up smaller, coherent blocks. 

The guideline for bundling code in functions is that the function should execute one single logical or functional action. Do not attempt to combine multiple actions.

You can call functions from within the same file, but also from other Python files. In that case you have to use the import directive first.

In the code below, we import three packages (datetime, calendar, locale). You can see that the function takes the current date and time and renders that to a given locale. That locale is given to the function as a parameter, so the function itself is fully internationalized. You can used named or unnamed parameters. The first one has the advantage that you do not have to pass parameters in the order specified in the function.

One thing to notice is that a function can return more than one result. This is one of the elegant features of Python. The object that is returned by the function below is a called a tuple.

import datetime
import calendar
import locale

def getDayDescription(thisLocale):
    locale.setlocale(locale.LC_ALL, thisLocale)
    nw = datetime.datetime.now()
    tm = nw.strftime('%H:%M')
    h = nw.strftime('%H')
    m = nw.strftime('M')
    dy = nw.strftime('%d')
    yr = nw.strftime('%Y')
    mo = nw.strftime('%B')
    wd = calendar.day_name[nw.weekday()]
    dat = (wd + ' ' + dy + ' ' + mo + ' ' + yr) #.capitalize()
    return dat, tm

dat, tm = getDayDescription('en-EN')
print(dat, tm)

# Same call, now with named arguments
dat, tm = getDayDescription(thisLocale = 'en-EN')
print(dat, tm)

Previous chapter | Next chapter