Think of a function whenever you want to do something specific. Let’s use your code as an example:
def areaTinta(altura, largura):
area = altura * largura
tinta = area / 2
print('-' * 50)
print(f'Serão necessários {tinta:.2f}l de tinta para pintar uma parede de {area:.2f}m².')
Your job is to do four different things,
- Calculate the area to be painted.
- Calculate the amount of paint needed.
- Display the
-
fifty times on the island.
- Display the message to the user stating the area to be painted and the amount of paint to be used.
Note that you have assigned various responsibilities to your role areaTinta()
, see that the function’s name by itself says a thing and the function proves other things.
Abstraction
Isolate something from the whole, isolate the operations contained in its function areaTinta()
. This applies as a form of generalization, whether with parameters or not. And bearing in mind that the function makes a only thing, we can isolate some parts of the whole.
Take the example:
def calcularArea(altura, largura):
return altura * largura
def calcularQuantidadeTinta(area):
return area / 2
I divided your function areaTinta()
in two, one that calculates only the receiving area as parameter altura
and largura
, and another that calculates the amount by dividing the area
for 2
, thus isolate the data processing in separate functions, giving more abstraction and meaning to the code.
And you apparently don’t need to display the message to the user within the function itself? Since there is no context, let’s use the function print
the overall scope of the programme.
Behold:
def calcularArea(altura, largura):
return altura * largura
def calcularQuantidadeTinta(area):
return area / 2
area = calcularArea(2, 6)
tinta = calcularQuantidadeTinta(area)
print(f'Serão necessários {tinta:.2f}l de tinta para pintar uma parede de {area:.2f}m².')
Exit
It will take 6.00l of paint to paint a wall of 12.00m².
Realized the difference now in the use of functions?
Note that now the two functions have assumed unique responsibilities, that is, to do a single thing. And it is interesting that you learn more about abstractions of functions and study about the DRY.