
A function in programming is a piece of structured and usable code. Each function performs a specific operation for us. With the help of functions, we can separate different parts of the program and give it more order. It is also easier to understand and modify codes. In this post, we will get to know the concept of programming function.
Una función en programación es una pieza de código estructurado y usable. Cada función realiza una operación específica para nosotros. Con la ayuda de funciones, podemos separar diferentes partes del programa y darle más orden. También es más fácil entender y modificar códigos. En este post vamos a conocer el concepto de función de programación.
No matter how much programming experience you have, you will always hear about and use functions. In this post, I am going to teach you the main concepts and the general structure of a function in programming without depending on a specific language.
No importa cuánta experiencia en programación tengas, siempre escucharás y usarás funciones. En este post te voy a enseñar los conceptos principales y la estructura general de una función en programación sin depender de un lenguaje específico.
Almost most programming languages and all widely used languages have the concept of function in them. It's just possible that the way it is written (its syntax) is different in different languages. In some languages, instead of function, words such as method, subroutine or procedure are used. But you should know that their concepts and principles are similar.
Casi la mayoría de los lenguajes de programación y todos los lenguajes ampliamente utilizados tienen el concepto de función en ellos. Es posible que la forma en que está escrito (su sintaxis) sea diferente en diferentes idiomas. En algunos idiomas, en lugar de función, se utilizan palabras como método, subrutina o procedimiento. Pero debes saber que sus conceptos y principios son similares.
First, we will talk about what a function is called in programming, and then we will review how to define and parts of programming functions together.
Primero, hablaremos sobre cómo se llama una función en programación, y luego revisaremos cómo definir y partes de funciones de programación juntas.
What is a function in programming?
The word function must be familiar to you. We always read about functions in math topics. Do you remember what we used to call a function in mathematics?
La palabra función debe resultarle familiar. Siempre leemos sobre funciones en temas matemáticos. ¿Recuerdas cómo solíamos llamar una función en matemáticas?
In a very simple view, a function is a box or a device that takes an input value, performs processing on it and produces an output; Just like a system.
En una vista muy simple, una función es una caja o un dispositivo que toma un valor de entrada, lo procesa y produce una salida; Como un sistema.
The programming function is defined in exactly the same way. Functions in programming perform operations after being called. Each function may have one or more inputs and outputs.
La función de programación se define exactamente de la misma manera. Las funciones en programación realizan operaciones después de ser llamadas. Cada función puede tener una o más entradas y salidas.

Similar to what you see in the picture, we look at functions as a box (or piece of code) that does things for us.
De manera similar a lo que ves en la imagen, vemos las funciones como un cuadro (o pieza de código) que hace cosas por nosotros.
Function in programming
Suppose we want to program a simple calculator. One way is to first take the input and then calculate the result based on the desired operator and with the help of conditional programming commands.
Supongamos que queremos programar una calculadora simple. Una forma es tomar primero la entrada y luego calcular el resultado en función del operador deseado y con la ayuda de comandos de programación condicionales.
You can probably imagine that we have to write many lines in a row. This will make it very difficult to debug or develop the application.
Probablemente puedas imaginar que tenemos que escribir muchas líneas seguidas. Esto hará que sea muy difícil depurar o desarrollar la aplicación.
Now suppose we want to define a complex mathematical operation (including addition, multiplication or division several times) in it. Do you agree that we will have to reuse addition, multiplication or division operators for our new operation?
Supongamos ahora que queremos definir una operación matemática compleja (incluyendo suma, multiplicación o división varias veces) en él. ¿Está de acuerdo en que tendremos que reutilizar los operadores de suma, multiplicación o división para nuestra nueva operación?
Compare this case with when we have to define a specific operation (like reading a file) in the program. To read the file, we must first open the file and close it after reading. If we want to do this again and again, the part of opening and closing the file will be repeated many times.
Compare este caso con cuando tenemos que definir una operación específica (como leer un archivo) en el programa. Para leer el archivo, primero debemos abrir el archivo y cerrarlo después de leerlo. Si queremos hacer esto una y otra vez, la parte de abrir y cerrar el archivo se repetirá muchas veces.
We use functions in programming so that we don't have to write repeated pieces of code to do the same or almost the same thing.
Utilizamos funciones en la programación para no tener que escribir fragmentos de código repetidos para hacer lo mismo o casi lo mismo.
The main parts of the programming function
A function in programming has four main parts. Note that these sections are the same in all languages. In some languages, there are other cases, which I will give an example at the end.
Una función en programación tiene cuatro partes principales. Tenga en cuenta que estas secciones son las mismas en todos los idiomas. En algunos idiomas, hay otros casos, de los cuales daré un ejemplo al final.
Function name
Each function must have a name. This name must be unique in each program. To call functions, we must use their names. Each programming language considers certain rules for the allowed characters in the function name definition; But in general, you can use English uppercase and lowercase letters, numbers and _
(underline).
Cada función debe tener un nombre. Este nombre debe ser único en cada programa. Para llamar funciones, debemos usar sus nombres. Cada lenguaje de programación considera ciertas reglas para los caracteres permitidos en la definición del nombre de la función; Pero, en general, puede usar letras mayúsculas y minúsculas en inglés, números y
_
(subrayado).
Be sure to read the documentation for its functions if you want to know what characters and structures are supported by the programs that work with it. For example, some languages don't allow putting a number at the beginning of a function name!
Asegúrese de leer la documentación de sus funciones si desea saber qué caracteres y estructuras son compatibles con los programas que funcionan con él. Por ejemplo, ¡algunos idiomas no permiten poner un número al principio del nombre de una función!
Usually, the function name is preceded by a word to indicate that we are defining the function. This word is different in different languages. For example, we use def
in Python and function
in PHP.
Por lo general, el nombre de la función va precedido de una palabra para indicar que estamos definiendo la función. Esta palabra es diferente en diferentes idiomas. Por ejemplo, usamos
def
en Python yfunction
en PHP.
Function body
Each function has a body. The body of the function in programming is exactly the piece of code that gives meaning to the existence of the function. What the function does is defined by the code in its body.
Cada función tiene un cuerpo. El cuerpo de la función en programación es exactamente la pieza de código que da sentido a la existencia de la función. Lo que hace la función está definido por el código en su cuerpo.
There is no specific criterion for the body size of functions. The amount of function codes can be one line or thousands of lines. But it is usually recommended to write the body in such a way that it is not too long.
No existe un criterio específico para el tamaño del cuerpo de las funciones. La cantidad de códigos de función puede ser de una línea o de miles de líneas. Pero normalmente se recomienda escribir el cuerpo de forma que no sea demasiado largo.
It is suggested that if you have a function with 100 lines of code that does two different things, it is better to split it into two smaller functions but with specific and unique tasks.
Se sugiere que si tiene una función con 100 líneas de código que hace dos cosas diferentes, es mejor dividirla en dos funciones más pequeñas pero con tareas específicas y únicas.
Function output and its type
In mathematics, the output of a function was the final value that was calculated. A function in programming can have an output or not! Let me make this clear with a simple example:
En matemáticas, el resultado de una función era el valor final que se calculaba. ¡Una función en programación puede tener una salida o no! Permítanme aclarar esto con un ejemplo simple:
If we write a function that counts the number of repetitions of a word in our text, that function will definitely have an output. The output of the function is the same number of repetitions.
Si escribimos una función que cuenta el número de repeticiones de una palabra en nuestro texto, esa función definitivamente tendrá una salida. La salida de la función es el mismo número de repeticiones.
But if we have a function that stores the value we want in the database, we may not need the result (success or failure of saving). If so, our function has no output.
Pero si tenemos una función que almacena el valor que queremos en la base de datos, es posible que no necesitemos el resultado (éxito o fracaso al guardar). Si es así, nuestra función no tiene salida.
Note that just because a function has no output doesn't mean it doesn't do anything special! In this database example, the output is not important to us, otherwise the function has done something important.
Tenga en cuenta que el hecho de que una función no tenga salida no significa que no haga nada especial. En este ejemplo de base de datos, la salida no es importante para nosotros; de lo contrario, la función ha hecho algo importante.
Programming function input
Functions in programming can have zero or more inputs. These input values are also called "function input parameters". In most programming languages, when defining a function, we can take any number of inputs with different names.
Las funciones en programación pueden tener cero o más entradas. Estos valores de entrada también se denominan "parámetros de entrada de funciones". En la mayoría de los lenguajes de programación, al definir una función, podemos tomar cualquier número de entradas con diferentes nombres.
Normally, when we say that the function add(x,y)
has two inputs, these two inputs are defined as mandatory. That is, if we call the function as add(5)
, we will encounter an error. It is also wrong if we call add(5,7,9)
.
Normalmente, cuando decimos que la función
add(x,y)
tiene dos entradas, estas dos entradas se definen como obligatorias. Es decir, si llamamos a la función comoadd(5)
, encontraremos un error. También está mal si llamamos aadd(5,7,9)
.
In most languages, it is also possible to define optional input parameters. That is, a function can have some mandatory and some optional inputs.
En la mayoría de los idiomas, también es posible definir parámetros de entrada opcionales. Es decir, una función puede tener algunas entradas obligatorias y algunas opcionales.

Other parts of the function structure
In different programming languages, sometimes we have to use unique features that exist in that language to define functions.
En diferentes lenguajes de programación, a veces tenemos que usar características únicas que existen en ese lenguaje para definir funciones.
For example, in the Java language, we must specify the access level of functions (methods). The meaning of access level is the same as public, private and protected status in object-oriented programming.
Por ejemplo, en el lenguaje Java, debemos especificar el nivel de acceso de las funciones (métodos). El significado del nivel de acceso es el mismo que el estado público, privado y protegido en la programación orientada a objetos.
Function definition in programming
Knowing the different parts of a programming function helps us recognize the function definition structure in any language. In general, if we want to put these parts together, we will have a structure like the following:
Conocer las diferentes partes de una función de programación nos ayuda a reconocer la estructura de definición de la función en cualquier lenguaje. En general, si queremos juntar estas partes, tendremos una estructura como la siguiente:
return_type function_name( parameters ){
//function body
return exp;
}
This type of definition is just an example and as I mentioned several times, the function definition syntax is different in each language.
Este tipo de definición es solo un ejemplo y como mencioné varias veces, la sintaxis de definición de funciones es diferente en cada idioma.
In this piece of code, I have used several keywords, the meaning and usage of each of which is as follows:
En este fragmento de código, he usado varias palabras clave, el significado y uso de cada una de ellas es el siguiente:
return_type
: Specifies the output data type. If our function has no output, we usually usevoid
.function_name
: The name of the function must be unique and unique throughout the program. Also, it is usually not possible to have a function with the name of a predefined function.parameters
: The input parameters are defined in this section.function body
: In this section, the body and function codes are placed.return exp
: With this command, we return the value ofexp
, which can be a variable, a message, or anything else, as the output of the function in each part of the function body.
In defining the input parameters, in some languages it is necessary to specify the type of each data. But in some languages, just writing the name of the input variable is enough. To define multiple input parameters in the function, we separate them with a comma (,
).
Al definir los parámetros de entrada, en algunos lenguajes es necesario especificar el tipo de cada dato. Pero en algunos idiomas, basta con escribir el nombre de la variable de entrada. Para definir múltiples parámetros de entrada en la función, los separamos con una coma (
,
).
For example, in the following code snippet, we have defined a function with three inputs in Python:
Por ejemplo, en el siguiente fragmento de código, hemos definido una función con tres entradas en Python:
def my_function( message, name, age ):
//do something
You can see Data types in programming
Calling programming functions
To call the function in programming, it is enough to name it wherever we need it and define the input parameters for it if needed.
Para llamar a la función en programación, basta con nombrarla donde la necesitemos y definir los parámetros de entrada si es necesario.
For a better understanding, suppose we define the power(x,y)
function in PHP language as follows to increase the number x
to the power of y
and give us as output.
Para una mejor comprensión, supongamos que definimos la función
power(x,y)
en lenguaje PHP de la siguiente manera para aumentar el númerox
a la potencia dey
y darnos como salida.
function power(x ,y){
return x**y;
}
So, wherever in the program we need, we must write power()
and define its two input values.
Entonces, en cualquier parte del programa que necesitemos, debemos escribir
power()
y definir sus dos valores de entrada.
power(2 ,8);
The output of this call will give us the number 256.
La salida de esta llamada nos dará el número 256.
Yo can see Variable Concept In Programming
Each program can have none or many functions. Where you should use the function or where you don't need to define the function in programming depends on your needs and creativity.
Cada programa puede tener muchas funciones o ninguna. Dónde debe usar la función o dónde no necesita definir la función en la programación depende de sus necesidades y creatividad.
But in general, if your program is long and consists of several parts that you can break into smaller functions, it is recommended to do this!
Pero, en general, si su programa es largo y consta de varias partes que puede dividir en funciones más pequeñas, ¡se recomienda hacer esto!
If you found this article informative, please give an upvote and rehive.
