User-defined Functions in Python

Programming is the art of teaching the computer to perform tasks that it was not previously capable of doing. One of the most interesting ways to achieve this is to add new instructions to the programming language you use, in the form of user-defined functions.

Defining a Function

The scripts you have written so far are very short, because their goal was to learn the basics of the language. As soon as you begin developing real projects, you will encounter many complex problems, and the lines of the program will start to accumulate…

An effective way to solve many problems is to divide them into smaller, simpler problems and study each one separately (these smaller problems can themselves be subdivided). It is important that these problems are properly divided into algorithms, and that they are clear.

On the other hand, the same sequence of instructions is often used repeatedly in a program, and it is not good to rewrite the code each time.

Functions and objects are different structures of subroutines imagined by programmers of high-level languages to solve the difficulties mentioned above. Here we will explain for the first time how to define functions in Python. We will discuss objects and classes later.

You have already encountered built-in functions used to perform various tasks. Now we will learn how to create our own functions.

Syntax for Defining a Function in Python

def functionName(parameter_list):
     ...
     instruction block
     ...
  • You can choose any name for the function you create, except reserved words of the language. You must not use symbols (except _), just like variable names. It is recommended to use lowercase letters most of the time, especially at the beginning of the name (names starting with uppercase letters are reserved for classes, which we will discuss later).
  • Like the if and while statements you already know, the def statement is a compound statement. The line containing it must end with a colon :, and it is followed by a block of instructions that must be indented.
  • The parameter list contains the information you want to pass to the function for use (the parentheses may be empty if the function does not need parameters).
  • The function is used like almost any instruction inside the program. It is called by its name followed by parentheses. If necessary, parameters are placed inside these parentheses. Usually, one parameter is defined in the function definition, although you can define default values for parameters (we will see this later).

A Simple Function Without Parameters

To make our first program applying functions, we will again use Python in interactive mode. Interactive mode is ideal for small tests like the following (this feature does not exist in all programming languages!):

def table7():
    n = 1
    while n < 11:
        print(n * 7, end=' ')
        n = n + 1

By entering these few lines, we have defined a very simple function that calculates and displays the first ten results of the multiplication table of 7.

Notice carefully the parentheses, the colon, and the indentation (the block that forms the body of the function itself).

To use the defined function, we simply call it by its name:

def table7():
  n=1 
  while n<11:
    print(n*7, end = ' ')
   	n = n + 1

This produces:

7 14 21 28 35 42 49 56 63 70

We can now reuse this function as many times as we want. We can also integrate it into another function, as in the following example:

def table7():
    n = 1
    while n < 11:
      print(n * 7, end=' ')
      n = n + 1

def table7triple():
    print('The table of 7 in triple form:')
    table7()
    table7()
    table7()
    

We can use this new function by entering table7triple():

def table7():
    n = 1
    while n < 11:
        print(n * 7, end=' ')
        n = n + 1

def table7triple():
    print('The table of 7 in triple form:')
    table7()
    table7()
    table7()
    
table7triple()

The output will be:

The table of 7 in triple form:
 7 14 21 28 35 42 49 56 63 70
 7 14 21 28 35 42 49 56 63 70
 7 14 21 28 35 42 49 56 63 70

A function can call another function, and the same applies to a third function, and so on.

At this stage, you may not yet fully see the usefulness of this, but we can already note two advantages:

  • Creating a new function allows us to give a name to a group of instructions. In this way, you can simplify the main body of the program by hiding a complex secondary algorithm behind a single instruction, which can be given a clear name.
  • Creating a new function allows us to reduce the size of the program by removing repeated parts. For example, if you want to display the table of 7 multiple times in the same program, you do not need to rewrite the algorithm each time.

A function is a new instruction of your own, which you can freely add to your programming language.

Function with Parameters

In the previous example, we defined and used a function that displays the multiplication table of 7. Now suppose that we need to do the same thing with the table of 9. Should we create a new function for this? And suppose also that we later want to do the same thing with the table of 13 — should we start over again? Would it not be better to define a function capable of displaying any table, on demand?

When we call this function, we must of course be able to specify which table we want to display. This information must be passed to the function and is called a parameter.

We have already encountered built-in functions that take parameters. The function sin(a), for example, computes the sine of the angle a. The function sin() therefore uses a numeric value as a parameter to perform its task.

In the function definition, there must be a special variable to receive the parameter. This variable is called a parameter variable. We choose its name according to the usual naming rules, and we place the name inside the parentheses associated with the function definition.

This is what we should write in our case:

def table(base):
    n = 1
    while n < 11:
        print(n * base, end=' ')
        n = n + 1 

The function table() as defined above uses the parameter base to calculate the first ten results of the corresponding multiplication table.

To test this new feature, we must call the function with a parameter. For example:

def table(base):
    n = 1
    while n < 11:
        print(n * base, end=' ')
        n = n + 1
                 
table (7)

13 26 39 52 65 78 91 104 117 130 
def table(base):
    n = 1
    while n < 11:
        print(n * base, end=' ')
        n = n + 1
                 
table (10)

9 18 27 36 45 54 63 72 81 90

In these examples, the value inside the parentheses when calling the function (that is, the parameter) is automatically assigned to the parameter variable base.

Inside the body of the function, base behaves like any other variable. When we write table(9), we mean that the machine executes the function table() by assigning the value 9 to the variable base.

Using a Variable as a Parameter

In the previous example, the parameter used for the function table() was each time a constant value (13, then 9). This is not mandatory. The parameter used when calling the function can also be a variable, as in the example below.

Study this example carefully, try to run it, and describe in your notebook what happens, explaining it clearly. This example gives you an initial idea of how functions can be used to perform complex tasks in a simple way:

a = 1
while a < 20:
    table(a)
    a = a + 1

Important Note

In the example above, the parameter that we passed to table() is the value contained in the variable a. Inside the function, this parameter is assigned to the parameter variable base, which is another variable.

Now note that:

The name of the variable passed as a parameter has no relation to the name of the corresponding parameter in the function.

These names may be the same if you wish, but you must understand that they do not represent the same thing (even though they may contain the same value).

Function with Multiple Parameters

The function table() is certainly interesting, but it only displays the first ten results of the multiplication table. Perhaps we want to display more than that.

Now we will improve the code by adding other parameters in a new version that we will call tableMulti():

def tableMulti(base, debut, fin):
	print('Fragment of the multiplication table of', base, ':')
	n = debut
 	while n <= fin:
		print(n, 'x', base, '=', n * base)
		n = n + 1 

This new function uses three parameters:

  • the first is the base of the table (as in the previous example),
  • the second is the starting multiplier,
  • the third is the ending multiplier.

Try this function by entering calling it by its name, for example:

def tableMulti(base, debut, fin):
	print('Fragment of the multiplication table of', base, ':')
	n = debut
 	while n <= fin:
		print(n, 'x', base, '=', n * base)
		n = n + 1 
tableMulti(8, 13, 17)  

It will display:

Fragment of the multiplication table of 8 :
 13 x 8 = 104
 14 x 8 = 112
 15 x 8 = 120
 16 x 8 = 128
 17 x 8 = 136

Notes

  • To define a function with multiple parameters, you must write them inside the parentheses following the function name, separated by commas.
  • When calling the function, the parameters must be in the correct order (and also separated by commas). The first parameter is assigned to the first parameter of the function, the second to the second, and so on.
  • As an exercise, try the following sequence of instructions and describe the result in your notebook:
t, d, f = 11, 5, 10
while t < 21:
	tableMulti(t, d, f)
	t, d, f = t + 1, d + 3, f + 5

In the next article, we will learn about lists in Python.

No Comments

Leave a Reply