def another_article(sweat,tears)
In this article you'll find:
- Introduction
- What is a function?
- What does a function look like in code?
- Why functions are important?
- A little example
In the first post of this series, I spoke superficially about functions when comparing them to methods. However, just explaining it this way would not do justice to one of the most used units of programming.
That is why, in the following article, we will talk in detail about functions, so that you can have a better command of them and understand perfectly what their "function" is.
Who knows, it may even save you some lines of code ;)
Let's start!
What is a function?
A function is a self-contained module within a program, which allows a task or series of tasks to be performed. Simply put, functions contain a task, which can be called from anywhere else in the program.
The way they work is that:
- They take the data that we introduce them.
- They execute the instructions that process the data.
- They return the result to the output.
Now that we know this, we deepen a little more in its operation. What happens when we call a function?
1.- The program is directed to a line of code that calls the function (function call).
2.- The program immediately goes to the first line of code inside the function.
3.- The instructions inside the function are executed.
4.- The program leaves the function and returns to the line of code where the function was called.
5.- The program adds the result of the function to the line of code instead of the function call.
6.- All done.
However, we are still left with the question: What does a function look like in code?
What does a function look like in code?
The way we define a function will change according to the programming language, however, the basic principles remain the same.
In this case, when using Python, we will have the keyword def followed by the function name, a list of parameters and the body of the function, where we write the instructions.
def function_1(parameter_list):
//// The instructions go here.
What is a parameter list? When we work with functions, in some cases we want to provide input values that the user or some other point in the program will assign, then the function will take these values, use them and return an output.
These input values are referenced through the use of parameters, which go inside the parentheses of the function. If, for example, we have a function that adds two numbers, we write the following:
number1 = 4
number2 = 3
def function_sum(num1, num2):
add_numbers = num1 + num2
return add_numbers
result = function_sum(number1, number2)
print(result)
We see that when executing the function on the variable result, we return def function_sum, where we are asked for two parameters. In this case, we will assign them the values of number1 and number2, which we defined previously.
Then, it will pass to the variable add_numbers that adds num1 (number1) and num2 (number2), and finally we return this variable. Then, we return to result that will have the sum of the numbers and when we print, we will have the following result:
>>> 7
Note: It is not mandatory for functions to have parameters. Just leave the parentheses empty and assign the instructions.
Why functions are important?
What do you think is easier to read and understand?
This:
list1 = [1,2,3,3,4,5]
list2 = [6,7,8,9,9,10]
list3 = [11,12,13,14,15]
new_list = []
for item in list1:
new_list.append(item)
print(new_list)
new_list.clear()
for item in list2:
new_list.append(item)
print(new_list)
new_list.clear()
for item in list3:
new_list.append(item)
print(new_list)
Or this:
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
list3 = [11,12,13,14,15]
def show_list(listobject):
new_list = []
for item in listobject:
new_list.append(item)
return new_list
print(show_list(list1))
print(show_list(list2))
print(show_list(list3))
Every programmer will choose the latter over the former. This is due to one of the main philosophies followed by computer enthusiasts: Don't Repeat Yourself or DRY.
By repeating lines of code we make the program more clumsy, we increase the probability of making mistakes and we use space that we could occupy with more important things. This is easily solved by defining functions, which allow us to reuse their code countless times just by calling them.
In addition, functions allow us to keep our variable namespace clean. This means that we can define variables with the same name as long as they are in different functions, eliminating confusion.
If we wanted to, we could separate our program into different functions, whose names describe the steps to be taken. Example: If we have a program for a registration page, we would simply create:
1.- A function to take the data entered (take_entered_data).
2.- A function to look for the data in the database class.
(search_data)
3.- A function that, if a previous user has not registered, allows us to enter (enter_user).
4.- A function that, in case that user exists, notifies us (existing_user).
Thus, by using functions we can save a lot of confusion and lines of code, giving us the simplicity of invoking it when we need it.
A little example
Let's say we have 3 articles and we want to move them to two different blog sites. In this case the articles are defined in a tuplad where the first value will be the title, the second will be the content of the article and the third will be the date of publication:
article = ('title','content','date')
Thus, for our 3 articles:
article1 = ("Python Coding", "Content of the Article", "08/17/2023")
article2 = ("Javascript Coding", "Content of the 2nd Article", "08/14/2023")
article3 = ("C# Coding", "Content of the 3rd Article", "08/15/2023")
And our two blogsites will be two empty lists:
blogsite1 = []
blogsite2 = []
Now, if we look at the instructions for handling lists (An article about this is coming soon), we can see that using the append() function, we can add new items to the list. So, to add an item to each blogsite, we would only have to use:
blogsite.append(article)
Now, we could use this for each new article and then run print to see if it was saved or just write this in a function like the following:
def write_for_site(article, blogsite):
for item in article:
blogsite.append(item)
print(f "Article added Now: {blogsite}")
We indicate the parameters of the article we select and the blogsite we choose, and then, by means of a for loop, save each of the elements of the article in the blogsite.
Now, to save the articles in the blogsite1, we only need to call the function and determine the variables that we will use (the parameters):
write_for_site(article1, blogsite1)
write_for_site(article2, blogsite1)
write_for_site(article3, blogsite1)
Thus, we would have the output:
>>>
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023']
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023', 'Javascript Coding', 'Content of the 2nd Article', '08/14/2023']
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023', 'Javascript Coding', 'Content of the 2nd Article', '08/14/2023', 'C# Coding', 'Content of the 3rd Article', '08/15/2023']
And for blogsite2:
write_for_site(article1, blogsite2)
write_for_site(article2, blogsite2)
write_for_site(article3, blogsite2)
>>>
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023']
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023', 'Javascript Coding', 'Content of the 2nd Article', '08/14/2023']
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023', 'Javascript Coding', 'Content of the 2nd Article', '08/14/2023', 'C# Coding', 'Content of the 3rd Article', '08/15/2023']
Functions are part of the basis of every program, allowing programmers to access the same instructions without having to write them over and over again, just by calling a function.
After this article, you will understand how and why functions are executed to help us. So feel free to experiment and add new details to your functions, as long as they help the goal of the program.
If you want to understand a little more about functions and how they are defined in different programming languages, just go to this article by Rishav Raj for dev.to
Thanks for your support and good luck!
def otro_articulo(sudor,lagrimas)
En este artículo encontrarás
- Introducción
- ¿Qué es una función?
- ¿Cómo luce una función en código?
- ¿Por qué son importantes las funciones?
- Un pequeño ejemplo
En el primer post de esta serie, hable superficialmente de las funciones al compararlas con los métodos. Sin embargo, solo explicarla de esta manera no le haría justicia a una de las unidades más usadas de la programación.
Es por esto, que en el siguiente artículo, hablaremos en detalle sobre las funciones, esto para que puedas tener un mayor dominio sobre estas y entender perfectamente cual es su función.
Quien sabe, incluso te ahorre algunas líneas de código ;)
!Comencemos!
¿Qué es una función?
Una función es un módulo autocontenido dentro de un programa, el cual permite realizar una tarea o serie de tareas. Dicho de una manera sencilla, las funciones contienen una tareas, la cual podemos llamar desde cualquier otro punto del programa.
La forma en que estas funcionan es que:
- Toman los datos que les introducimos.
- Ejecutan las instrucciones que procesan los datos.
- Nos devuelven el resultado a la salida.
Ahora que sabemos esto, profundizamos un poco más en su funcionamiento. Que pasa cuando llamamos una función?
1.- El programa se dirige a una línea de código que llama la función (function call).
2.- El programa se dirige inmediatamente a la primera línea de código dentro de la función.
3.- Las instrucciones dentro de la función son ejecutadas.
4.- El programa deja la función y regresa a la línea de código donde se llamo la función.
5.- El programa agrega la línea de código el resultado de la función en vez del function call.
6.- Todo listo.
Sin embargo, aún nos queda la duda: ¿Como luce una función en código?
¿Como se ve una función en código?
La forma en que definimos una función cambiará de acuerdo al lenguaje de programación, sin embargo, los principios básicos se mantienen.
En este caso, al usar Python, tendremos la keyword def seguida por el nombre de la función, una lista de parámetros y el cuerpo de la función, donde escribimos las instrucciones.
def function_1(parameter_list):
//// Las instrucciones van aquí
¿Qué es una lista de parámetros? Cuando trabajamos con funciones, en algunos casos queremos proporcionar valores de entrada que el usuario o algún otro punto del programa asignará, entonces, la función tomará estos valores, los usará y nos devolverá una salida.
Estos valores de entrada se referencian por medio del uso de parámetros, los cuales van dentro de los paréntesis de la función. Si por ejemplo, tenemos una función que suma dos números, escribimos lo siguiente:
number1 = 4
number2 = 3
def function_sum(num1, num2):
add_numbers = num1 + num2
return add_numbers
result = function_sum(number1, number2)
print(result)
Vemos que al ejecutar la función en la variable result, retornamos a def function_sum, donde nos piden dos parámetros. En este caso, les asignaremos los valores de number1 y number2, que ya definimos previamente.
Entonces, pasará a la variable add_numbers que suma num1 (number1) y num2 (number2), y finalmente retornamos esta variable. Entonces, volvemos a result que tendrá la suma de los números y al hacer print, tendremos el siguiente resultado:
7
Nota: No es obligatorio que las funciones tengan parámetros. Solo basta con dejar los paréntesis vacíos y asignar las instrucciones.
¿Por qué son importantes las funciones?
¿Que piensas que es más facil de leer y entender?
Esto:
list1 = [1,2,3,3,4,5]
list2 = [6,7,8,9,9,10]
list3 = [11,12,13,14,15]
new_list = []
for item in list1:
new_list.append(item)
print(new_list)
new_list.clear()
for item in list2:
new_list.append(item)
print(new_list)
new_list.clear()
for item in list3:
new_list.append(item)
print(new_list)
O esto:
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
list3 = [11,12,13,14,15]
def show_list(listobject):
new_list = []
for item in listobject:
new_list.append(item)
return new_list
print(show_list(list1))
print(show_list(list2))
print(show_list(list3))
Todo programador escogerá la segunda ante la primera. Esto es debido a una de las principales filosofías que siguen los amantes de la computación: Don't Repeat Yourself o DRY.
Al repetir líneas de código hacemos el programa más tosco, aumentamos la probabilidad de cometer errores y usamos espacio que podríamos ocupar con cosas más importantes. Esto se soluciona facilmente al definir funciones, que nos permiten reutilizar su código incontables veces con tan solo llamarlas.
Además, las funciones nos permiten mantener nuestro variable namespace limpio. Esto significa que podemos definir variables con el mismo nombre siempre y cuando se encuentren en funciones distintas, eliminando la confusión.
Si quisieramos, podríamos separar nuestro programa en distintas funciones, cuyo nombre describa los pasos a tomar en cuenta. Ejemplo: Si tenemos un programa para una página de registro, simplemente crearíamos:
1.- Una función para tomar los datos introducidos. (take_entered_data)
2.- Una función para buscar los datos en la clase de la base de datos.
(search_data)
3.- Una función que, de no haber registrado un usuario anterior, nos permita entrar (enter_user)
4.- Una función que, en caso de existir ese usuario nos lo notifique (existing_user)
Así, por medio del uso de funciones podemos ahorrarnos una gran cantidad de confusión y líneas de código, dándonos la simpleza de invocarla cuando la necesitemos.
Un pequeño ejemplo
Digamos que tenemos 3 artículos y queremos pasarlos a dos sitios de blogs distintos. En este caso los artículos están definidos en una tupladonde el primer valor será el título, el segundo será el contenido del artículo y el tercero la fecha de publicación:
article = ('title','content','date')
Así, para nuestros 3 artículos:
article1 = ("Python Coding", "Content of the Article", "08/17/2023")
article2 = ("Javascript Coding", "Content of the 2nd Article", "08/14/2023")
article3 = ("C# Coding", "Content of the 3rd Article", "08/15/2023")
Y nuestros dos blogsites serán dos listas vacías:
blogsite1 = []
blogsite2 = []
Ahora, si nos fijamos en las instrucciones para el manejo de listas (Pronto un artículo sobre esto), podemos ver que usando la función append(), podemos agregar nuevos elementos a la lista. Así, para añadir un artículo a cada blogsite, solo tendríamos que usar:
blogsite.append(article)
Ahora, podríamos usar esto para cada nuevo artículo y luego ejecutar print para ver si se grabo o simplemente escribir esto en una función como la siguiente:
def write_for_site(article, blogsite):
for item in article:
blogsite.append(item)
print(f"Article added \n Now: {blogsite}")
Le indicamos los parámetros del artículo que seleccionemos y del blogsite que escojamos, para luego, por medio de un ciclo for, grabar cada uno de los elementos del artículo en el blogsite.
Ahora, para grabar los artículos en el blogsite1, solo basta con llamar a la función y determinar las variables que usaremos (los parámetros):
write_for_site(article1, blogsite1)
write_for_site(article2, blogsite1)
write_for_site(article3, blogsite1)
Así, tendríamos a la salida:
>>>
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023']
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023', 'Javascript Coding', 'Content of the 2nd Article', '08/14/2023']
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023', 'Javascript Coding', 'Content of the 2nd Article', '08/14/2023', 'C# Coding', 'Content of the 3rd Article', '08/15/2023']
Y para el blogsite2:
write_for_site(article1, blogsite2)
write_for_site(article2, blogsite2)
write_for_site(article3, blogsite2)
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023']
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023', 'Javascript Coding', 'Content of the 2nd Article', '08/14/2023']
Article added
Now: ['Python Coding', 'Content of the Article', '08/17/2023', 'Javascript Coding', 'Content of the 2nd Article', '08/14/2023', 'C# Coding', 'Content of the 3rd Article', '08/15/2023']
Las funciones forman parte de la base de cada programa, permitiendo a los programadores acceder a las mismas instrucciones sin tener que escribirlas una y otra vez, solo con llamar a una función.
Después de este artículo, podrás entender como y por qué las funciones se ejecutan para auxiliarnos. De esta forma, siéntete libre de experimentar y añadir nuevos detalles a tus funciones, siempre y cuando ayuden a la meta del programa.
Si quieres entender un poco más sobre las funciones y saber como se definen en distintos lenguajes de programación, solo tienes que acceder a este artículo de Rishav Raj para dev.to
Gracias por tu apoyo y ¡Buena suerte!