Mini-Sistema de Registro de Deportistas usando archivos [ESP-ENG] | Python

in Develop Spanish11 months ago

¡Buenos días! Aquí estoy de nuevo con otra publicación sobre Python, el lenguaje de programación que estoy aprendiendo esta temporada. Esta vez, el ejercicio encomendado fue bastante más complicado que los anteriores.

Podría decirse que fue un pequeño proyecto, pues es un sistema de registro de deportistas. El enunciado es el siguiente:

Crear un programa en Python que permita:

a) Registrar los datos de un deportista de una disciplina deportiva de su agrado.

b) Listar el archivo en forma ordenada.

c) Mostrar un deportista dado su nombre.

d) Eliminar un deportista.

Good morning! Here I am again with another post about Python, the programming language I am learning this season. This time, the assigned exercise was quite more complicated than the previous ones.

You could say it was a small project, since it is a system for recording athletes. The statement is as follows:

Create a program in Python that allows:

(a) Register the data of an athlete of a sport discipline of your liking.

b) List the file in an orderly fashion.

c) Display an athlete given his name.

d) Delete an athlete.


Portada post programacion, tech (5).gif
Edited with CANVA

Education separador png.png

Entrando en materia, comencé importando la librería "os", pues necesitaría llamar algunas funciones relacionadas al manejo de archivos que incluye dicha librería.

Luego cree la función "selector", que si vieron la sentencia Switch-Case en C++, les recordará bastante, pues funciona a modo de "copia", pues con un diccionario, usando como claves los números del 1 al 5, relacione cada una de las opciones que puede elegir el usuario. El "default", sería "opción inválida", es decir, si no ingresa un numero del 1-5, ese será el retorno.

Posteriormente sigue una función para validar números enteros a la que llamé "Int_validador", con "n" y "msj" como parámetros. Funciona habilitando la entrada por teclado con un mensaje personalizado para luego tratar de convertirla en entero. Si se ingresa algo que no sea numero o que incluya decimales en caso de serlo, se lanzará un mensaje de error y se volverán a pedir los datos.

La función "Pausa_LimpiarPantalla()", es bastante sencilla pero redujo significativamente la redundancia. Esta aprovecha la sentencia input() para realizar un pausa hasta que el usuario ingrese otra cosa y luego limpia la consola con "os.system("cls").

El menú fue la cuarta función, esta no tiene parámetros pues no los necesita. Este sería el centro del programa, pues agrupa todas las funciones solicitadas, se apoya en todas las anteriormente mencionadas e incluye un bucle para que el programa no se cierre cuando el usuario termine de ejecutar una de las funciones en el rango 1-4. En esta función coloqué una variable booleana llamada "key", inicializada en True, para controlar el bucle while principal que fue el que acabo de mencionar. Este bucle comienza con un for que muestra la información del pseudo-switch-case, de modo que el usuario pueda saber cuáles son las funciones disponibles y a que número están asociadas.

Posteriormente llega Int_Validador para verificar que la opción que ingrese el usuario sea efectivamente un número, esto también tiene un bloque if-else para varificar que no se salga del rango. En la variable "accion" se recibe la opcion elegida por el usuario, para posteriormente entrar a un bloque if-else con 5 opciones, cada una descritas en el selector. La primera opción es para agregar, esta se habilita cuando se ingresa 1 y empieza con la recolección de los datos: Nombre, apellido, edad, cedula y deporte.

De todos esos datos se validan la edad y la cedula que son numéricos, el resto no tiene un bloque de validación, aunque bien se podría agregar si se desea. Una vez se registran los datos se procede a unirlos todos en una cadena que luego se ingresa a un archivo con la sentencia open() y luego write() a un objeto de tipo archivo. El nombre es "Deportistas.txt", aunque se le puede colocar el que se desee.

Eso va dentro de un bloque try-except, para capturar las posibles excepciones al tratar de abrir el archivo. Seguidamente está la opción 2, que se habilita como es de esperarse con el número 2. Esta se encarga de Ordenar y mostrar. Para ello se inicia un bloque try-except que verifica si se pudo ejecutar exitosamente la apertura del archivo y se pudieron guardar sus datos en una lista.

Entering in matter, I began importing the library "os", because I would need to call some functions related to the handling of files that includes this library.

Then I created the function "selector", that if you saw the Switch-Case statement in C++, it will remind you a lot, because it works as a "copy", because with a dictionary, using as keys the numbers from 1 to 5, relate each of the options that the user can choose. The "default", would be "invalid option", that is, if you do not enter a number from 1-5, that will be the return.

Then follows a function to validate integers which I called "Int_validator", with "n" and "msj" as parameters. It works by enabling keyboard input with a custom message and then trying to convert it to integer. If something is entered that is not a number or includes decimals if it is, an error message will be thrown and the data will be requested again.

The function "Pause_CleanScreen()", is quite simple but significantly reduced redundancy. It takes advantage of the input() statement to pause until the user enters something else and then clears the console with "os.system("cls").

The menu was the fourth function, this one has no parameters because it does not need them. This would be the center of the program, because it groups all the requested functions, it is supported in all the previously mentioned and includes a loop so that the program does not close when the user finishes executing one of the functions in the range 1-4. In this function I placed a boolean variable called "key", initialized to True, to control the main while loop which was the one I just mentioned. This loop begins with a for that shows the information of the pseudo-switch-case, so that the user can know which are the available functions and to which number they are associated.

Then comes Int_Validador to verify that the option entered by the user is indeed a number, this also has an if-else block to verify that it does not go out of range. In the variable "action" the option chosen by the user is received, to later enter an if-else block with 5 options, each one described in the selector. The first option is to add, this is enabled when 1 is entered and begins with the collection of data: Name, last name, age, ID and sport.

Of all these data, the age and ID are validated, which are numeric, the rest does not have a validation block, although it could be added if desired. Once the data is registered, we proceed to join them all in a string that is then entered into a file with the open() sentence and then write() to a file type object. The name is "Deportistas.txt", although it can be given any name you wish.

That goes inside a try-except block, to catch possible exceptions when trying to open the file. Next is option 2, which is enabled as expected with the number 2. This one is in charge of Sort and display. For this purpose, a try-except block is started to check if the file could be successfully opened and its data could be saved in a list.

Education separador png.png

image.png

image.png

image.png

image.png

image.png

Education separador png.png

Posteriormente, con un bucle for se ordena la lista y luego se imprima en pantalla. Algo que me faltó mencionar es que cada parametro de texto alfanumérico (nombre, apellido y deporte) ingresado se pasa por upper() para facilitar luego su búsqueda.

Y es precisamente esa opción la que sigue, la número 3 que corresponde a búsqueda. Esta empieza recibiendo el nombre de aquel deportista que se busca, luego se pasa por upper(), para asegurar que todas las letras estén en mayúsculas y sea más fácil la ubicación respecto a los registros. Luego de esto se entra a un bucle try-except que se cubre los posibles errores al abrir el archivo, leer sus líneas y guardarlas en una lista llamada "listaTodos" y declarar una lista vacía.

Posteriormente se entra a un bucle for (si se ejecuta exitosamente le try, se va al else) que itera en "listaTodos" y va guardando sus elementos en la lista auxiliar, quitando los "-", que separan los registros, de modo que la búsqueda sea más efectiva. Posteriormente se guarda el contenido de la lista correspondiente al bloque a partir del nombre buscado ingresado por el usuario, en una lista llamada "n_busca" y se itera sobre ella para mostrar los datos requeridos. Cada uno junto a un identificador que se imprime en el momento justo gracias a un bloque if-else que va controlando la palabra "Nombre", "Apellido", "Edad", y así sucesivamente según el número de iteración.

Para la opción 4 aparece la función eliminar, en esta se inicia con un bloque try-except que controla los posibles errores al tratar de abrir el archivo y guardar sus registros en una lista, luego itera en esa lista para quitar los "-" que separan los elementos para así facilitar la comparación y luego en un bloque if-else comprueba que el registro a eliminar exista para removerlo si es posible.

Posteriormente se actualiza el archivo con la sentencia write() y se cierra. Seguidamente se muestra en pantalla un mensaje que informa que el registro se ha eliminado con éxito y se limpia la pantalla. La última opción es salir, que rompe el bucle y envía un mensaje de despedida.

Subsequently, with a for loop the list is sorted and then printed on the screen. Something I forgot to mention is that each alphanumeric text parameter (name, surname and sport) entered is passed through upper() to facilitate later its search.

And it is precisely that option that follows, the number 3 that corresponds to search. This starts by receiving the name of the athlete being searched, then it is passed through upper(), to ensure that all letters are capitalized and easier to locate with respect to the records. After this we enter a try-except loop that covers possible errors by opening the file, reading its lines and saving them in a list called "listAll" and declaring an empty list.

Subsequently, we enter a for loop (if the try loop is successfully executed, we go to the else loop) that iterates in "listAll" and saves its elements in the auxiliary list, removing the "-", which separates the records, so that the search is more effective. Subsequently, the contents of the list corresponding to the block from the searched name entered by the user are saved in a list called "n_search" and iterates over it to display the required data. Each one together with an identifier that is printed at the right time thanks to an if-else block that controls the word "First name", "Last name", "Age", and so on according to the iteration number.

For option 4 appears the delete function, which starts with a try-except block that controls the possible errors when trying to open the file and save its records in a list, then iterates in that list to remove the "-" that separate the elements to facilitate the comparison and then in an if-else block checks that the record to be deleted exists to remove it if possible.

The file is then updated with the write() statement and closed. Then a message is displayed on the screen informing that the record has been successfully deleted and the screen is cleared. The last option is to exit, which breaks the loop and sends a goodbye message.

Education separador png.png

image.png

image.png

image.png

image.png

Education separador png.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

Education separador png.png

Y bueno, nada más que agregar, este ha sido mi proyecto de un pequeño sistema de registro de atletas, hay funciones que se pueden optimizar bastante como la de búsqueda, siguiendo la estructura de la función eliminar, pero lo cierto es que no tengo tanto tiempo en este momento. En la función eliminar me apoyé en los apuntes de un compañero de la materia pues la idea que yo tenía era mucho más complicada y no lograba plasmarla exitosamente, sin embargo, él me mostro un camino más sencillo para llegar a la solución. Desde acá te mando un saludo don Luis, éxitos y gracias por el apoyo. De verdad que es de provecho tener compañeros para corregir el código mutuamente y mejorar en el proceso.

Si andas buscando un buen curso de este lenguaje conocido como Python, en lo personal te recomiendo este: Clica aquí.

And well, nothing more to add, this has been my project of a small system of registration of athletes, there are functions that can be optimized enough as the search, following the structure of the delete function, but the truth is that I do not have so much time at the moment. In the delete function I relied on the notes of a classmate because the idea I had was much more complicated and I could not successfully translate it, however, he showed me a simpler way to reach the solution. From here I send you a greeting Don Luis, success and thanks for the support. It is really helpful to have partners to correct each other's code and improve the process.

If you are looking for a good course on this language known as Python, I personally recommend you this one: Click here

Education separador png.png

Redes actualizada.gif


Puedes seguirme por acá si lo deseas:
You can follow me here if you want:

Cuenta secundaria
(Dibujos, edición y juegos) | Secondary account (Drawings, editing and games)

Sort:  

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

¡Gracias por el apoyo!

Muchas gracias por compartir con nosotros amigo, saludos ❣️

Gracias a ti por pasar por acá