How to move to a function for better organization in Python

1

Good I have several parts of code that I want to pass to functions and I need a brief explanation with an example of a portion of my code:

from xlrd import open_workbook

book = open_workbook("archivo.xlsx")
for sheet in book.sheets():
    for rowidx in range(sheet.nrows):
        row = sheet.row(rowidx)
        for colidx, cell in enumerate(row):
            if cell.value == 4072:
                var = str(row[2])
                print(var)

How can I change to a function that? thanks

    
asked by Giacomo F 19.10.2018 в 22:32
source

1 answer

4

A function is just a block of code with a name, but it has the particularity of being able to receive parameters and return results.

The general form is (in this example it receives two parameters):

def nombre_funcion(par1, par2):
    bloque de código
    que puede acceder a las variables par1, par2
    que puede contener return expresion

When you invoke the function like this: nombre_funcion(expr1, expr2) , the code block of the function will be executed and the variables par1 par2 within the function will have the values you have set in expr1 , expr2 when calling her.

If the function contains return expresion , the result of evaluating that expression will be the returned value. At the invocation point you can receive that result and assign it to a variable, for example:

result = nombre_funcion(expr1, expr2)

In your case, converting the code into a function can be as simple as this (in this case it does not receive any parameter or return any results):

def obtener_valores():
    book = open_workbook("archivo.xlsx")
    for sheet in book.sheets():
        for rowidx in range(sheet.nrows):
            row = sheet.row(rowidx)
            for colidx, cell in enumerate(row):
                if cell.value == 4072:
                    var = str(row[2])
                    print(var)

But we would be underutilizing the potential of the functions. It can be useful that the file name is a parameter, and thus the same function would be used to process different files. It can also be useful if the special number 4072 is another parameter and so the function would be useful to find other numbers. Finally I see that you print something that is in column 2 of the row. That 2 could be another parameter so that the function could show another column.

In general, where you see "preset expressions" in your code, it may be useful to change them by parameters so that the function is usable in more scenarios.

It would stay like this:

def obtener_valores(excel, dato, col):
    book = open_workbook(excel)
    for sheet in book.sheets():
        for rowidx in range(sheet.nrows):
            row = sheet.row(rowidx)
            for colidx, cell in enumerate(row):
                if cell.value == dato:
                    var = str(row[col])
                    print(var)

And you would call it like this:

obtener_valores("archivo.xlsx", 4072, 2)

You can also make use of the possibility that python offers you to give default values to the parameters, so you do not have to specify them in the call. So:

def obtener_valores(excel, dato=4072, col=2):
    book = open_workbook(excel)
    for sheet in book.sheets():
        for rowidx in range(sheet.nrows):
            row = sheet.row(rowidx)
            for colidx, cell in enumerate(row):
                if cell.value == dato:
                    var = str(row[col])
                    print(var)

I have left the first parameter as mandatory, so that must always be put when calling the function, but the other two are optional and if you do not put them, they will take the default value. Thus, any of the following syntax is possible when calling it:

obtener_valores("archivo.xlsx")            # dato sería 4072 y col sería 2
obtener_valores("archivo.xlsx", 4000)      # dato sería 4000 y col sería 2
obtener_valores("archivo.xlsx", 4000, 3)   # dato sería 4000 y col sería 3
obtener_valores("archivo.xlsx", col=3)     # dato sería 4072 y col sería 3
obtener_valores("archivo.xlsx", dato=4010) # dato sería 4010 y col sería 2

Finally, this function does not return results but rather it prints the data as it finds them. What if instead of printing them we would like to add them all? Or how many are? Or ...? (you understand me)

It would be better if the function instead of printing things, simply return it and that either the main program decides what to do with that data.

We can therefore change the function so that it creates a list in which it will keep the data it finds, to finally return that list:

def obtener_valores(excel, dato=4072, col=2):
    book = open_workbook(excel)
    encontrados = []
    for sheet in book.sheets():
        for rowidx in range(sheet.nrows):
            row = sheet.row(rowidx)
            for colidx, cell in enumerate(row):
                if cell.value == dato:
                    var = str(row[col])
                    encontrados.append(var)
    return encontrados

If you now call the function (with any of the above syntaxes), nothing will appear on the screen. But you can save the result in a variable and use it for whatever you want. For example, print it:

resultado = obtener_valores("archivo.xlsx")  # dato sería 4072 y col sería 2
print("Encontrados", len(resultado), "valores")
for dato in resultado:
    print(dato)
    
answered by 19.10.2018 / 22:54
source