Basic programming course: Lesson #6 Functions. [ESP-ENG]

in #devwithseven2 days ago

lesson 6.jpg

Creado con canva

ESP

Untitled design.png


Funciones


Estamos llegando ya al final de este curso, a pesar de qué nos van a faltar algunas estructuras un poco más complejas, he podido enseñarles a lo largo de toda esta temporada las cosas más básicas que incluyen la mayoría de lenguaje de programación y que nos ayudan a resolver problemas de cualquier índole prácticamente en el mundo.

La última estructura que veremos en este curso serán las funciones, uno de los elementos más importantes a la hora de programar ya que nos permiten reutilizar cualquier parte del código de forma dinámica. Las funciones son una manera de reutilizar un bloque de código para una tarea específica permitiéndonos organizar el código de una manera modular y que sea fácil de entender y mantener.

Te has puesto a pensar en cómo funciona tu cerebro, por ejemplo, cuando quieres sumar dos números normalmente no debes repasar todo el concepto y el proceso que realizar una operación de suma conlleva, por el contrario simplemente tomas los dos números que deseas sumar y con la experiencia que ya tienes simplemente realizas la operación y consigues el resultado. Algo así funcionan las funciones valga la redundancia, te permite empaquetar procesos y poderlos utilizarlos luego dandole valores específicos para la situación.

En programación hay dos tipos de funciones, las funciones sin valor de retorno y las funciones con valor de retorno. Las funciones sin valor de retorno son funciones que realizan el proceso pero no devuelven al programa principal alguna información, una vez se ejecutan simplemente termina el proceso. Las funciones con valor de retorno son funciones que utilizamos para realizar alguna operación y conseguir un resultado, como por ejemplo la de la suma.

Vamos a crear una función para sumar 2 números, que además retorna el resultado de la suma al proceso principal. Para ello, fuera de nuestro algoritmo vamos a utilizar la siguiente estructura:

Funcion

FinFuncion

Después de la palabra Funcion vamos a colocar la variable adónde se va a retornar el resultado, en este caso nuestra variable se va a llamar result. Esa variable la igualaremos al nombre de la función, en este caso la función la llamaremos sumar, y entre paréntesis vamos a colocar los datos que va a recibir la función para funcionar, en este caso los dos números que llamaremos n1 y n2, a estos datos se le conocen como parámetros.

Funcion result = sumar(n1, n2)

FinFuncion

Dentro de la función vamos a realizar todo el proceso deseado. En este caso tenemos que declarar la variable result que es donde vamos a almacenar el resultado de la suma, y realizar la operación. En este caso los números no se declaran en la función porque se reciben como parámetros, por lo que suponemos que los vamos a enviar desde el algoritmo principal.

Funcion result = sumar(n1, n2)
        Definir result Como Real;
        result = n1 + n2; 
FinFuncion

Ahora en el algoritmo principal vamos a declarar las variables de los números y a solicitarla al usuario. Después de pedir los números vamos a llamar a la variable que devuelve la función, en este caso no es necesario declararla ya que ya la declaramos en la propia función. Después llamamos al nombre de la función y le pasamos los valores que ya guardamos en las variables de los números. Finalmente imprimimos el resultado de sumar.

Algoritmo funciones
    Definir n1, n2 Como Real;
    Imprimir "Ingresa un numero:";
    Leer n1;
    Imprimir "Ingresa un numero:";
    Leer n2;
    
    result = sumar(n1,n2);
    
    Imprimir "La suma de ambos numeros es de: " result;
FinAlgoritmo

Con esta función logramos conseguir un valor de regreso al algoritmo principal. Podemos ver esto de forma más claras y ejecutamos el programa:

Captura de pantalla 2024-10-12 a la(s) 1.51.37 p. m..png

Ahora, también tenemos funciones que no retornan nada y sirven simplemente para realizar algún proceso como mostrar un mensaje o algo parecido. Imagínate que en lugar de imprimir directamente el resultado tenemos una función que se encarga de esto, esta funciona la llamaremos mostrarResultado.

Funcion mostrarResultado(r)
    Imprimir "La suma de ambos numeros es de: " r;
FinFuncion

En este caso no igualamos la función a ninguna variable ya que no devolverá ningún valor, simplemente se encargará de imprimir el mensaje con el resultado, por parámetro le decimos que va a recibir una variable llamada r, le modifiqué el nombre para que vean más o menos como funciona.

Ahora en el algoritmo principal simplemente llamamos la fundación y le pasamos la variable result.

mostrarResultado(result);

Acá podemos ver como el resultado del programa es el mismo pero hemos empaquetado dos de la características en funciones que se pueden utilizar infinidad de veces para realizar esta misma tarea de forma dinámica. Puede que con programas de este estilo tan pequeños no le veas mucha utilidad pero en programas grandes y complejos suelen ser muy útiles.

Captura de pantalla 2024-10-12 a la(s) 6.54.14 p. m..png


Ejercicio


Vamos a crear una pequeña calculadora utilizando funciones, uno de los ejemplos más utilizados para poder explicar este tema y que se comprenda mucho mejor el contenido. Para este ejercicio empaquetado prácticamente la mayoría de cosas que se pueden empaquetar en funciones para utilizarlas en el algoritmo principal. Éste es el código:

Funcion opt = mostrarMenu
    Imprimir "Que desea hacer?";
    Imprimir "1. Sumar.";
    Imprimir "2. Restar.";
    Imprimir "0. Salir.";
    Leer opt;
FinFuncion

Funcion n = pedirNumero(n)
    Imprimir "Ingresa un numero:";
    Leer n;
FinFuncion

Funcion mostrarResultado(r)
    Imprimir "El resultado de la operacion es " r;
FinFuncion

Funcion reiniciar
    Imprimir "Presione cualquier tecla para continuar.";
    Esperar Tecla;
    Limpiar Pantalla;
FinFuncion

Funcion  result = sumar (n1, n2)
    Definir result Como Real;
    result = n1 + n2; 
FinFuncion

Funcion  result = restar (n1, n2)
    Definir result Como Real;
    result = n1 - n2; 
FinFuncion

Algoritmo calc
    Definir n1,n2 Como Real;
    Definir opt Como Entero;
    Definir exit Como Logico;
    
    exit = Falso;
    
    Repetir 
        opt = mostrarMenu();
        
        Segun opt Hacer
            caso 0: 
                Limpiar Pantalla;
                Imprimir "Bye =)";
                exit = Verdadero;
            caso 1:
                n1 = pedirNumero(n1); 
                n2 = pedirNumero(n2); 
                result = sumar(n1,n2); 
                mostrarResultado(result); 
                reiniciar();
            caso 2:
                n1 = pedirNumero(n1); 
                n2 = pedirNumero(n2);
                result = restar(n1,n2); 
                mostrarResultado(result); 
                reiniciar();
            De Otro Modo:
                Imprimir "Opcion invalida."; 
                reiniciar();
        FinSegun
        
    Hasta Que exit
FinAlgoritmo
  • Empezamos con las funciones mostrarMenu, que retorna un resultado lógico después de leer la opción que el usuario va a escoger en la calculadora y de mostrar el menú completo en Pantalla. Esta función no tiene parámetros entonces no se le colocan los paréntesis.
  • Seguimos con la función pedirNumero, que recibe por parámetro la variable que vamos a leer y muestra un mensaje solicitando al usuario e ingresar un número. Con esta función podemos mostrar el mensaje y leer la variable al mismo tiempo.
  • Seguimos con una función para mostrar los resultados simplemente, ésta recibe por parámetro el resultado y muestra el mensaje en Pantalla como en el ejemplo anterior.
  • Creamos una función llamada reiniciar donde mostramos el mensaje indicando de qué presione una tecla cualquiera para continuar y limpiamos la Pantalla para volver a mostrar al Menu una vez se presiona cualquier tecla.
  • Seguimos con las funciones de suma y resta, las dos retornan el resultado tal como vimos en el ejemplo.
  • A partir de acá el algoritmo comienza y simplemente tenemos el menú con un ciclo hacer-mientras, se lee la opción a través de una estructura según, y dentro de cada caso se van llamando las funciones necesarias.

Tips para ser un buen programador


Antes de finalizar este curso me gustaría dejar algunos consejos para las personas que deseen seguir profundizando en el tema de la programación, estos consejos servirán sobre todo para crear mejores códigos y para seguir creciendo en este amplio mundo. Éste es sólo un primer paso, pero una vez domines la lógica básica utilizar cualquier lenguaje de programación será un trabajo mucho más sencillo, ya que ellos en esencia se basan en estas estructuras.

  • Práctica frecuentemente, programar es como tener un músculo, debes entrenarlo frecuentemente para poder progresar y realizar cosas muchos más complejas, nunca dejes de aprender y de realizar proyectos que te desafíen a ti mismo para seguir ampliando tus conocimientos.
  • Escoge un buen lenguaje de programación, no hay un lenguaje definitivo, cada uno tiene su uso específico. Evalúa qué es lo que deseas hacer e investiga qué lenguaje de programación podría adecuarse a tus necesidades. Por ejemplo si tú deseas crear sitios web quizás puedas optar por JavaScript y PHP; si deseas crear aplicaciones de escritorio podrías considerar utilizar Java o C#; y de esta manera cada área del mundo la tecnología tiene sus propios lenguajes que sirven para crear en ellas.
  • Lee código de otros, cómo programador te enfrentarás muchas veces a trabajar sobre programas que ya fueron creados previamente, por lo que leer código de otros te ayudará a desarrollar tu habilidad de comprensión y podrás trabajar sobre estos códigos sin problemas. Además el conocer como otras personas resuelven problemas específicos puede ayudarte a aprender a hacerlo tú cuando te estanques.
  • Crea, y no borres, anteriormente mencioné que crees proyectos para ti mismo, una vez los termines no los borres. Generalmente los programadores no comienzan de cero las tecnologías que van a crear, reutilizar código que puedes ya haber creado en el pasado es algo que agilizará mucho tu tiempo y te hará más productivo.

Tarea


  • Cuéntanos sobre tu experiencia con la programación, ¿Fue tu primera vez? ¿Te resulto complicado? ¿Cual fue tu parte favorita del curso? (2 puntos)
  • Agrega a la calculadora del curso las funciones para multiplicar y dividir. Explica como lo hiciste. (3 puntos)
  • PROYECTO FINAL: Crea un simulador de cajero automático. El mismo debe solicitar inicialmente un pin de acceso al usuario, este pin es 12345678. Una vez el pin sea validado exitosamente debe mostrar un menu que permita: 1. ver saldo, 2. depositar dinero, 3. retirar dinero, 4. salir. El cajero no debe dejar retirar mas saldo del que se posee. Utiliza todas las estructuras que aprendiste, y funciones. (5 puntos)
Puedes consultar las clases anteriores:
Basic programming course: Lesson #1 - Introduction to programming [ESP-ENG]
Basic programming course: Lesson #2 - Variables and Types of Data [ESP-ENG]
Basic programming course: Lesson #3 Operations [ESP-ENG]
Basic programming course: Lesson #4 Control structures. Part 1. Conditionals. [ESP-ENG]
Basic programming course: Lesson #5 Control structures. Part 2. Cycles. [ESP-ENG]

Normas


  • El contenido debe ser #steemexclusive.
  • El artículo debe contener la etiqueta #devjr-s20w6.
  • El plagio no está permitido.
  • El link de tu tarea debe ser agregado en los comentarios de esta publicación.
  • El curso estará abierto durante 7 días a partir de las 00:00 UTC del 20 de Octubre. Después de la fecha limite los usuarios podrán seguir participando sin optar a premios con el objetivo de permitir a mas personas en el tiempo de aprovechar este contenido.

ENG

Untitled design.png


Functions


We are already reaching the end of this course, despite the fact that we will lack some slightly more complex structures, I have been able to teach you throughout this season the most basic things that include most programming language and that help us solve problems of any kind practically in the world.

The last structure that we will see in this course will be the functions, one of the most important elements when programming since they allow us to reuse any part of the code dynamically. Functions are a way to reuse a block of code for a specific task allowing us to organize the code in a modular way that is easy to understand and maintain.

You have started thinking about how your brain works, for example, when you want to add two numbers you usually should not review the whole concept and the process that performing a sum operation entails, on the contrary you simply take the two numbers you want to add and with the experience you already have you simply perform the operation and get the result. Something like this works the functions worth the redundancy, it allows you to package processes and be able to use them then giving them specific values for the situation.

In programming there are two types of functions, functions without return value and functions with return value. Functions without return value are functions that perform the process but do not return some information to the main program, once they are executed they simply end the process. Functions with return value are functions that we use to perform an operation and achieve a result, such as the addition.

We are going to create a function to add 2 numbers, which also returns the result of the addition to the main process. To do this, outside of our algorithm we will use the following structure:

Function

EndFunction

After the word Function we are going to place the variable where the result is going to be returned, in this case our variable is going to be called result. We will match that variable to the name of the function, in this case we will call the function sum, and in parentheses we will place the data that the function will receive to work, in this case the two numbers that we will call n1 and n2, these data are known as parameters.

Function result = sum(n1, n2)

EndFunction

Within the function we will carry out the entire desired process. In this case we have to declare the result variable which is where we are going to store the result of the sum, and perform the operation. In this case the numbers are not declared in the function because they are received as parameters, so we assume that we are going to send them from the main algorithm.

Function result = sum(n1, n2)
        Define result As Real;
        result = n1 + n2; 
EndFunction

Now in the main algorithm we are going to declare the variables of the numbers and request it from the user. After asking for the numbers we are going to call the variable that returns the function, in this case it is not necessary to declare it since we already declare it in the function itself. Then we call the name of the function and pass the values that we already save in the variables of the numbers. Finally we print the result of adding.

Algorithm functions

   Define n1, n2 As Real; 
   Print "Enter a number:"; 
   Read n1; 
   Print "Enter a number:"; 
   Read n2;

   result = sum(n1,n2); 
   Print "The sum of both numbers is from: " result;

EndAlgorithm

With this function we manage to get a value back to the main algorithm. We can see this more clearly and run the program:

Captura de pantalla 2024-10-12 a la(s) 1.51.37 p. m..png

Now, we also have functions that do not return anything and simply serve to perform some process such as showing a message or something similar. Imagine that instead of directly printing the result we have a function that takes care of this, this works we will call it showResult.

Function showResult(r)
    Print "The sum is: " r;
EndFunction

In this case we do not match the function to any variable since it will not return any value, it will simply be responsible for printing the message with the result, by parameter we tell you that you will receive a variable called r, I changed the name so that you can see more or less how it works.

Now in the main algorithm we simply call the foundation and pass it the variable result.

showResult(result);

Here we can see how the result of the program is the same but we have packaged two of the features in functions that can be used countless times to perform this same task dynamically. You may not see much use for programs of this style so small, but in large and complex programs they are usually very useful.

Captura de pantalla 2024-10-12 a la(s) 6.54.14 p. m..png


Exercise


We are going to create a small calculator using functions, one of the most used examples to be able to explain this topic and to understand the content much better. For this exercise, practically most things that can be packaged in functions to use in the main algorithm. This is the code:

Function opt = showMenu
    Print "What do you want to do?";
    Print "1. Sum.";
    Print "2. Subtract.";
    Print "0. Exit.";
    Read opt;
EndFunction

Function n = askNum(n)
    Print "Enter a number:";
    Read n;
EndFunction

Function showResult(r)
    Print "The result is " r;
EndFunction

Function reset
    Print "Press any key to continue.";
    Wait Key;
    Clear Screen;
EndFunction

Function  result = sum (n1, n2)
    Define result As Real;
    result = n1 + n2; 
EndFunction

Function  result = subtract (n1, n2)
    Define result As Real;
    result = n1 - n2; 
EndFunction

Algorithm calc
    Define n1,n2 As Real;
    Define opt As Integer;
    Define exit As Logic;
    
    exit = False;
    
    Repeat 
        opt = showMenu();
        
        Switch opt Do
            case 0: 
                Clear Screen;
                Print "Bye =)";
                exit = True;
            case 1:
                n1 = askNum(n1); 
                n2 = askNum(n2); 
                result = sum(n1,n2); 
                showResult(result); 
                reset();
            case 2:
                n1 = askNum(n1); 
                n2 = askNum(n2);
                result = subtract(n1,n2); 
                showResult(result); 
                reset();
            Default:
                Print "Invalid option."; 
                reset();
        EndSwitch
        
    While !exit
EndAlgorithm
  • We start with the showMenu functions, which returns a logical result after reading the option that the user will choose in the calculator and showing the entire menu on Screen. This function has no parameters so the parentheses are not placed.
  • We continue with the askNum function, which receives by parameter the variable that we are going to read and shows a message asking the user to enter a number. With this function we can display the message and read the variable at the same time.
  • We continue with a function to show the results simply, it receives the result by parameter and shows the message on Screen as in the previous example.
  • We create a function called reset where we show the message indicating what to press any key to continue and we clean the Screen to show the Menu again once any key is pressed.
  • We continue with the addition and subtraction functions, the two return the result as we saw in the example.
  • From here the algorithm starts and we simply have the menu with a do-while cycle, the option is read through a structure according to, and within each case the necessary functions are called.

Tips to be a good programmer


Before finishing this course I would like to leave some tips for people who wish to continue deepening the subject of programming, these tips will serve above all to create better codes and to continue growing in this wide world. This is only a first step, but once you master the basic logic using any programming language will be a much simpler job, since they are essentially based on these structures.

  • Practice frequently, programming is like having a muscle, you must train it frequently to be able to progress and do much more complex things, never stop learning and carrying out projects that challenge yourself to continue expanding your knowledge.
  • Choose a good programming language, there is no definitive language, each one has its specific use. Evaluate what you want to do and investigate what programming language could suit your needs. For example, if you want to create websites, you may be able to opt for JavaScript and PHP; if you want to create desktop applications you could consider using Java or C#; and in this way each area of the world technology has its own languages that serve to create in them.
  • Read other people's code, as a programmer you will often face working on programs that were previously created, so reading other people's code will help you develop your understanding skills and you will be able to work on these codes without problems. In addition, knowing how other people solve specific problems can help you learn how to do it yourself when you get stuck.
  • Create, and do not delete, I previously mentioned that you create projects for yourself, once you finish them do not delete them. Generally, programmers do not start from scratch the technologies they are going to create, reusing code that you may have already created in the past is something that will speed up your time a lot and make you more productive.

Homework


  • Tell us about your experience with programming, was it your first time? Did you find it complicated? What was your favorite part of the course? (2 points)
  • Add the functions to multiply and divide to the course calculator. Explain how you did it. (3 points)
  • FINAL PROJECT: Create an ATM simulator. It must initially request an access pin to the user, this pin is 12345678. Once the pin is successfully validated, it must show a menu that allows: 1. view balance, 2. deposit money, 3. withdraw money, 4. exit. The cashier should not allow more balance to be withdrawn than is possessed. Use all the structures you learned, and functions. (5 points)
You can check the previous classes:
Basic programming course: Lesson #1 - Introduction to programming [ESP-ENG]
Basic programming course: Lesson #2 - Variables and Types of Data [ESP-ENG]
Basic programming course: Lesson #3 Operations [ESP-ENG]
Basic programming course: Lesson #4 Control structures. Part 1. Conditionals. [ESP-ENG]
Basic programming course: Lesson #5 Control structures. Part 2. Cycles. [ESP-ENG]

Rules


  • The content must be #steemexclusive.
  • The article must contain the tag #devjr-s20w6.
  • Plagiarism is not allowed.
  • The link of your task must be added in the comments of this publication.
  • The course will be open for 7 days from 00:00 UTC on October 20. After the deadline, users will be able to continue participating without applying for prizes with the aim of allowing more people in time to take advantage of this content.
Sort:  
Loading...

This post has been upvoted by @italygame witness curation trail


If you like our work and want to support us, please consider to approve our witness




CLICK HERE 👇

Come and visit Italy Community



Hi @alejos7ven,
my name is @ilnegro and I voted your post using steem-fanbase.com.

Come and visit Italy Community

Coin Marketplace

STEEM 0.18
TRX 0.16
JST 0.030
BTC 65941.36
ETH 2622.37
USDT 1.00
SBD 2.67