tutorial net
*********WOOOOOOW *********
We're happy to see you're enjoying our races (already 5 pages viewed today)! You can keep checking out by becoming a member of the tutorial net community. It's free!
You will also be able to keep track of your race progress, practice on exercises, and chat with other members.

Share
Go down
Admin
Posts : 207
Join date : 2017-11-11
Age : 27
Location : algeria
View user profilehttp://www.tutorial-net.com

tutorial Python - Step by step to modularity Python

on 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:
Code:
def nom_de_la_fonction(parametre1, parametre2, parametre3, parametreN):
    # Bloc d'instructions
Blocks of instructions run after us too, what a hell. If we dissect the definition line of the function, we find in order:

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.
When you run this code on the screen, nothing happens. Once you have found the three chevrons, try calling the function:
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
>>>
Well, it's, uh, exactly what we've managed to do in the previous chapter and the interest is not yet obvious. The advantage is that you can easily call the function and redisplay the whole table without having to rewrite everything!

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.
And there, you can pass in different numbers argument, table(8)to display the multiplication table by 8 for example.

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
If you type now  table(11, 20), the interpreter will show you the table of 11, from 1 * 11 to 20 * 11. Magic no?

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
Just add =10after max. Now you can call the function in two ways: either by specifying the table number and the maximum number of displays, or by specifying only the number of the table ( table(7)). In the latter case, it maxwill be 10 by default.

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()
In line 1 we define the function exemple. It is called a first time on line 4. We redefine on line 6 the function exemple. The old definition is overwritten and the old function can no longer be called.

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 instruction returnmeans that we will return the value, so that we can retrieve it and store it in a variable for example. This statement stops the flow of the function, the code after it will returnnot run.
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.
Back to top
Permissions in this forum:
You cannot reply to topics in this forum