A Gentle Introduction to Functions Using Python

Functions are a common feature of almost every programming language out there, be it Python, Java, Javascript, Golang, C, C++, or some other language with its own set of defined rules and syntax. Functions enable you to carry out a particular task multiple times and anywhere within your program, without you having to write the code on every occasion.

Functions are important because they enable us to keep our code DRY- Don't Repeat Yourself. Lol. DRY is a programming convention that suggests you should not repeat the same code multiple times within your program, and every good programmer knows this.

From the foregoing discussion, we can describe a function more technically as a reusable block of code. Next, we see how to create functions.

How to Create a Function

Every programming language has its unique syntax for creating or defining functions. In Python, a function can be created in these steps:

Step One: Define the function name and include its parameters(if any).

Step Two: (Optional) Briefly describe what the function does.

Step Three: Write the code block and return any values where necessary.

(1)  def func_name(parameters):
(2)       """"function description""""
(3)       code block

From the above, the first step in creating a function in Python is to define its name using the def keyword. Enclosed within the parentheses are optional parameters that may be required for the function to execute. Parameters are inputs/variables that may be needed for the function to run. As we shall see later, not every function requires parameters and so the parentheses can be left empty. (Even so, the parentheses are a must). Finally, the definition ends in a colon.

Any indented lines that follow the function's def line make up the body of the function.

The second step in creating a function is to write a docstring, which is a string of text that briefly describes what the function does. The docstring is enclosed in triple quotes as shown in the snippet above. Also, the docstring is optional i.e. you mustn't include a docstring in your function; however, they are important for the documentation of the functions in your program.

Every other line within the indented function body is the actual block of code and this can be made up of single or multiple lines of code depending on what the function does. The third step, therefore, entails (correctly) writing the necessary code that will perform the required task.

For our first example, let us write a function that simply calculates the average of any three numbers.

def avg(a, b, c):
     """"This function calculates the average of three numbers""""
     d = (a + b + c)/3
     return d

The variables a, b, and c are the parameters of a function named avg. They represent any three numbers whose average we want to calculate.

Also, notice the last line of code which has the return keyword. The return keyword is used if a function is expected to 'give back' a value at the end of its execution. In this case, the returned value is the variable d which represents the calculated average.

That being said, not every function returns a value. Some functions only print/display something on the screen. See the next example:

def greet():
      """"Display a simple greeting""""
      print('Hello!')

The above function named greet simply prints the text Hello! when executed. The function did not require any inputs, hence the empty parentheses. We can modify the function a little bit to print Hello and also the name of a person. Consequently, we have to include a parameter, say, name to represent the name of any person.

def greet(name):
      print('Hello,' + name + '!')

Observe that a docstring was not included this time but the function will work just fine.

Using a Function

You can make use of a function in your program by making a function call. This simply means writing the function name and then enclosing any required arguments in parentheses, where applicable. An argument is just a specific value passed a parameter, in order. If no parameters were included in the function definition, then no arguments are needed when making the function call.

Say we want to obtain the average of three numbers: 2, 4, and 6. We call the avg function as follows:

avg(2, 4, 6)

returns:

4

Using the greet function, you might want to print(display) a string of text: Hello<your name>! thus:

greet(Chimex)

displays:

Hello, Chimex!

Please note that you can call a function anywhere outside the body of the function and not within it.

Finally...

Functions can either be user-defined or built-in. Whenever you use a function whose code you did not write yourself, the function is said to be built-in. Virtually every language comes pre-loaded with several built-in functions. Examples of built-in functions in Python are the print() function for displaying a string of text, and the len() function for obtaining the length of a string or list-type data.

User-defined functions on the other hand are functions you create by yourself within your program. The sample functions we wrote above are user-defined.

Different functions perform different tasks and some functions are certainly more complicated to develop than others, but the underlying principles remain the same:

                  Define the function

                  Describe it (if you want)

                  Write the code

Start writing functions today. Using functions makes your program easier to write, test, and fix.