tutorial Python - Step by step to modularity Python
Sun Apr 01, 2018 10:31 am
In programming, it is often necessary to use several groups of instructions for a very specific purpose. Be careful, I'm not talking about loops here. Simply, you will realize that most of our tests can be grouped into larger blocks, functions or modules. I will quietly detail these two concepts.
The functions make it possible to group several instructions in a block which will be called thanks to a name. Moreover, you have already seen functions: printand inputare part of it for example.
The modules make it possible to group several functions according to the same principle. All mathematical functions, for example, can be placed in a module dedicated to mathematics.
The functions: it's up to you
We have used a lot of functions since the beginning of this tutorial. For the record print, typeand inputnot to mention a few others. But you must realize that there are countless functions already built in Python. However, you will also find that very often a programmer creates his own functions. This is the first step you will take in this chapter towards modularity . This somewhat barbarous term means that we will get used to regrouping in parts of our code that we will have to reuse. In the next chapter, we will learn how to group our related functions in a file, to form a module, but do not anticipate.
Creating functions
We will, to illustrate this example, take again the code of the multiplication table, which we saw in the previous chapter and which, decidedly, does not finish to continue you.
We will imprison our code calculating the multiplication table by 7 in a function we will call table_par_7.
We create a function according to the following scheme:
def, keyword which is the abbreviation of "define" and which constitutes the prelude to any construction of function.
The name of the function, which is named exactly as a variable (we will see later that it is not by chance). Do not use an instantiated variable name to name a function.
The list of parameters that will be provided during a call to the function. The parameters are separated by commas and the list is enclosed by opening and closing parentheses (again, spaces are optional but improve readability).
The two points, again and again, that close the line.
Parentheses are mandatory, even if your function does not wait for any parameter.
The code to put our multiplication table by 7 in a function would be:
But, if we enter parameters to be able to display the table of 5 or 8 ...?
Yes, it would be much more useful. I do not think you have too much trouble finding the function code:
One can also consider passing in parameter the number of values to be displayed in the table.
In the case where one uses several parameters without naming them, as here, it is necessary to respect the order of call of the parameters, that goes without saying. If you start putting the number of displays as the first parameter while in the definition it was the second, you may have some surprises. It is possible to call the parameters in the disorder but it is necessary, in this case, to specify their name: we will see that further.
Default values of the parameters
You can also specify a default value for the parameters of the function. For example, you can specify that the maximum number of views should be 10 by default (that is, if the user of your function does not specify it). It is most simply done in the world:
I took the opportunity to add a few lines of explanations that you will undoubtedly have noticed. We placed a string of characters, without capturing it in a variable, just below the function definition. This chain is what we call one docstringthat could be translated by a chain of help. If you type help(table), this is the message you will see. Documenting your duties is also a good habit to take. As you can see, we indent this string and put it in triple quotation marks. If the string is on a single line, we can put the three quotation marks on the same line; otherwise, we prefer to skip a line before closing this string, for readability reasons. All the text of
Finally, know that we can call parameters by name. This is useful for a function that has a number of parameters that all have a default value. You can also use this method on a function without a default setting, but it is less common.
Signature of a function
The term "function signature" means the elements that enable the language to identify said function. In C ++, for example, the signature of a function consists of its name and the type of each of its parameters. This means that you can find several functions with the same name but different settings. At the time of the function call, the compiler looks for the function that applies to that signature.
In Python, as you can see, we do not specify the types of parameters. In this language, the signature of a function is simply its name. This means that you can not define two functions of the same name (if you do, the old definition is overwritten by the new one).
Just remember that, as for variables, a function name only refers to a single function, you can not overload functions in Python.
The instructionreturn
What we did was interesting, but we have not seen the possibilities of the function yet. And besides, even at the end of this chapter, we will have some small features to see. If you remember, there are functions like that printthat do not return anything (be careful, "send" and "show" are two different things) and functions such as inputor typereturn a value. You can capture this value by placing a variable in front (example variable2 = type(variable1)). Indeed, the functions generally work on data and return the result obtained, following a calculation for example.
Let's take a simple example: a function that squares a value passed as an argument. I note in passing that Python is perfectly capable without coding a new function, but it is for the example.
The variable variablewill contain, after execution of this instruction, 5 squared, that is to say 25.
Be aware that we can return multiple values that are separated by commas, and that we can capture them in variables also separated by commas, but I will dwell later on this feature. Just remember the definition of a function, the parameters, the default values, the instruction returnand it will be good.
Lambda functions
We have just seen how to create a function thanks to the keyword def. Python offers us another way to create functions, extremely short functions because they are limited to a single instruction.
Why another way to create functions? The first is enough, right?
Let's say it's not quite the same thing, as you'll see. The lambda functions are usually used in a certain context, for which to define a function with the help of defwould be longer and less convenient.
The functions make it possible to group several instructions in a block which will be called thanks to a name. Moreover, you have already seen functions: printand inputare part of it for example.
The modules make it possible to group several functions according to the same principle. All mathematical functions, for example, can be placed in a module dedicated to mathematics.
The functions: it's up to you
We have used a lot of functions since the beginning of this tutorial. For the record print, typeand inputnot to mention a few others. But you must realize that there are countless functions already built in Python. However, you will also find that very often a programmer creates his own functions. This is the first step you will take in this chapter towards modularity . This somewhat barbarous term means that we will get used to regrouping in parts of our code that we will have to reuse. In the next chapter, we will learn how to group our related functions in a file, to form a module, but do not anticipate.
Creating functions
We will, to illustrate this example, take again the code of the multiplication table, which we saw in the previous chapter and which, decidedly, does not finish to continue you.
We will imprison our code calculating the multiplication table by 7 in a function we will call table_par_7.
We create a function according to the following scheme:
- Code:
def nom_de_la_fonction(parametre1, parametre2, parametre3, parametreN):
# Bloc d'instructions
def, keyword which is the abbreviation of "define" and which constitutes the prelude to any construction of function.
The name of the function, which is named exactly as a variable (we will see later that it is not by chance). Do not use an instantiated variable name to name a function.
The list of parameters that will be provided during a call to the function. The parameters are separated by commas and the list is enclosed by opening and closing parentheses (again, spaces are optional but improve readability).
The two points, again and again, that close the line.
Parentheses are mandatory, even if your function does not wait for any parameter.
The code to put our multiplication table by 7 in a function would be:
- Code:
def table_par_7():
nb = 7
i = 0 # Notre compteur ! L'auriez-vous oublié ?
while i < 10: # Tant que i est strictement inférieure à 10,
print(i + 1, "*", nb, "=", (i + 1) * nb)
i += 1 # On incrémente i de 1 à chaque tour de boucle.
- Code:
>>> table_par_7()
1 * 7 = 7
2 * 7 = 14
3 * 7 = 21
4 * 7 = 28
5 * 7 = 35
6 * 7 = 42
7 * 7 = 49
8 * 7 = 56
9 * 7 = 63
10 * 7 = 70
>>>
But, if we enter parameters to be able to display the table of 5 or 8 ...?
Yes, it would be much more useful. I do not think you have too much trouble finding the function code:
- Code:
def table(nb):
i = 0
while i < 10: # Tant que i est strictement inférieure à 10,
print(i + 1, "*", nb, "=", (i + 1) * nb)
i += 1 # On incrémente i de 1 à chaque tour de boucle.
One can also consider passing in parameter the number of values to be displayed in the table.
- Code:
def table(nb, max):
i = 0
while i < max: # Tant que i est strictement inférieure à la variable max,
print(i + 1, "*", nb, "=", (i + 1) * nb)
i += 1
In the case where one uses several parameters without naming them, as here, it is necessary to respect the order of call of the parameters, that goes without saying. If you start putting the number of displays as the first parameter while in the definition it was the second, you may have some surprises. It is possible to call the parameters in the disorder but it is necessary, in this case, to specify their name: we will see that further.
Default values of the parameters
You can also specify a default value for the parameters of the function. For example, you can specify that the maximum number of views should be 10 by default (that is, if the user of your function does not specify it). It is most simply done in the world:
- Code:
def table(nb, max=10):
"""Fonction affichant la table de multiplication par nb
de 1*nb à max*nb
(max >= 0)"""
i = 0
while i < max:
print(i + 1, "*", nb, "=", (i + 1) * nb)
i += 1
I took the opportunity to add a few lines of explanations that you will undoubtedly have noticed. We placed a string of characters, without capturing it in a variable, just below the function definition. This chain is what we call one docstringthat could be translated by a chain of help. If you type help(table), this is the message you will see. Documenting your duties is also a good habit to take. As you can see, we indent this string and put it in triple quotation marks. If the string is on a single line, we can put the three quotation marks on the same line; otherwise, we prefer to skip a line before closing this string, for readability reasons. All the text of
Finally, know that we can call parameters by name. This is useful for a function that has a number of parameters that all have a default value. You can also use this method on a function without a default setting, but it is less common.
Signature of a function
The term "function signature" means the elements that enable the language to identify said function. In C ++, for example, the signature of a function consists of its name and the type of each of its parameters. This means that you can find several functions with the same name but different settings. At the time of the function call, the compiler looks for the function that applies to that signature.
In Python, as you can see, we do not specify the types of parameters. In this language, the signature of a function is simply its name. This means that you can not define two functions of the same name (if you do, the old definition is overwritten by the new one).
- Code:
def exemple():
print("Un exemple d'une fonction sans paramètre")
exemple()
def exemple(): # On redéfinit la fonction exemple
print("Un autre exemple de fonction sans paramètre")
exemple()
Just remember that, as for variables, a function name only refers to a single function, you can not overload functions in Python.
The instructionreturn
What we did was interesting, but we have not seen the possibilities of the function yet. And besides, even at the end of this chapter, we will have some small features to see. If you remember, there are functions like that printthat do not return anything (be careful, "send" and "show" are two different things) and functions such as inputor typereturn a value. You can capture this value by placing a variable in front (example variable2 = type(variable1)). Indeed, the functions generally work on data and return the result obtained, following a calculation for example.
Let's take a simple example: a function that squares a value passed as an argument. I note in passing that Python is perfectly capable without coding a new function, but it is for the example.
- Code:
def carre(valeur):
return valeur * valeur
The variable variablewill contain, after execution of this instruction, 5 squared, that is to say 25.
Be aware that we can return multiple values that are separated by commas, and that we can capture them in variables also separated by commas, but I will dwell later on this feature. Just remember the definition of a function, the parameters, the default values, the instruction returnand it will be good.
Lambda functions
We have just seen how to create a function thanks to the keyword def. Python offers us another way to create functions, extremely short functions because they are limited to a single instruction.
Why another way to create functions? The first is enough, right?
Let's say it's not quite the same thing, as you'll see. The lambda functions are usually used in a certain context, for which to define a function with the help of defwould be longer and less convenient.
Permissions in this forum:
You cannot reply to topics in this forum