Function Overview

A function in Python is a section of reusable code that takes an argument, or arguments, does some computations, and returns the result of the computations. There are two types, built-in functions, and user defined functions.

A built-in function is a function that comes with Python, or with a library for Python (Pandas, SciPy, NumPy, etc.). Some examples of these are: min(), max(), len(), str(), int(), float(), and so many more.

A user defined function is created by the user. They are created using the “def” reserved word. The general structure of a user defined function looks like this:

def my_func(argument):
    do stuff
    do more stuff
    give result

 

To use a function, one must call it. This is done by using the function name and entering the argument(s).

my_func(argument_passed)

Function Example

The first function that will be shown will take a numeric argument, multiply it by 10, and return the result.

def times_ten(number):
    return number*10
        
times_ten(9)
90

 

Next example will have logic used in the function. The result returned will depend on the argument given.

def word_size(word):
    if len(word) > 5:
        return "That's a decent sized word"
    else:
        return "Think of a bigger word"

word_size("Hey")
‘Think of a bigger word’

 

word_size("Brilliant")
“That’s a decent sized word”

 

Functions are very useful when working with Pandas data frames and needing to recode a variable, or to apply a mathematical computation. These examples will be provided under the Pandas section once you learn about what it is, that way it will make more sense.