Cálculo del factorial de un número [ESP-ENG] | Python

¡Buenos días! Aquí estoy de vuelta con otra publicación sobre programación, esta vez, con otro clásico de los ejercicios iniciales y que al igual que otros que he traído de este lenguaje, lo he tratado antes en C++.

El enunciado es tan simple como "Cálculo del factorial de un número". Con un bucle for se resuelve sin mayor problema, sin embargo, existe un detalle a considerar y es la validación de los datos que ingrese el usuario por teclado.

Good morning! Here I am back with another post about programming, this time, with another classic of the initial exercises and that like others that I have brought from this language, I have dealt with it before in C++.

The statement is as simple as "Calculating the factorial of a number". With a for loop it is solved without major problem, however, there is a detail to consider and it is the validation of the data that the user enters by keyboard.


Portada post programacion, tech (4).gif

Education separador png.png

El código es realmente corto en comparación a la calculadora de factoriales que hice en C++, cosa que es lógica considerando las características de Python, pero no por ello quiere decir que este último sea superior en todo a C++.

Entrando en materia, el programa se basa en dos funciones y el respectivo llamado de ambas con un print final para mostrar los resultados obtenidos. La primera función se llama "Factorial", y como es lógico pensar, calcula el factorial de un número que se le ingrese por parámetro. Sin embargo, no lo valida, de esto se encarga la siguiente función.

Factorial(n), cuenta con una variable "a", inicializada con valor "1", que será quien almacene el cálculo realizado en el for. Este itera desde 1, hasta n+1, esto para evitar que cuente el 0, pues de ser así, al multiplicar el iterador por la variable "a", el resultado se vería afectado para mal.

Por otro lado, la función "Read_n", se encarga de leer un número, este al principio se transforma en cadena de texto para facilitar su manipulación, pues luego se tratará de convertir a entero en un bloque de tratamiento de excepciones, en donde la operación es, n1 = (int)(n1), es decir, la conversión.

Si se convierte sin problemas (esto incluye el rechazo a números decimales como 5,4), pasa a otra validación, la de rango, pues no se puede calcular el factorial de un número negativo y además, incluí un máximo de 500, pues, aunque se pueden calcular factoriales superiores, el tamaño es sumamente grande.

Finalmente se llama a la función Read_n(), para almacenar su retorno en una variable "n", y luego se imprime el factorial con la función print("El factorial del numero ingresado es: ", Factorial(n)).

Mientras armaba este programa, me encontré con que no lograba que funcionase como deseaba el bloque Try-Except-Else, por lo que tuve que investigar un poco y ver ejemplos antes de aplicarlo. La página que consulté se llama freecodecamp.org.

The code is really short compared to the factorial calculator that I made in C++, which is logical considering the characteristics of Python, but it does not mean that the latter is superior in everything to C++.

Getting into the subject, the program is based on two functions and the respective call of both with a final print to show the results obtained. The first function is called "Factorial", and as it is logical to think, it calculates the factorial of a number that is entered by parameter. However, it does not validate it, this is taken care of by the following function.

Factorial(n), has a variable "a", initialized with value "1", which will store the calculation performed in the for. This iterates from 1 to n+1, this to avoid counting the 0, because if so, when multiplying the iterator by the variable "a", the result would be affected for bad.

On the other hand, the function "Read_n", is in charge of reading a number, this at the beginning is transformed into text string to facilitate its manipulation, because then it will try to convert to integer in an exception handling block, where the operation is, n1 = (int)(n1), that is to say, the conversion.

If it is converted without problems (this includes the rejection to decimal numbers like 5,4), it passes to another validation, the range validation, because the factorial of a negative number cannot be calculated and also, I included a maximum of 500, because, although higher factorials can be calculated, the size is extremely large.

Finally, the function Read_n() is called, to store its return in a variable "n", and then the factorial is printed with the function print("The factorial of the number entered is: ", Factorial(n)).

While i made this program, I found that I could not get the Try-Except-Else block to work the way I wanted it to, so I had to do some research and look at examples before applying it. The page I consulted is called freecodecamp.org.

Education separador png.png

image.png

Education separador png.png

image.png

Education separador png.png

Y bueno... ¡Eso es todo por hoy! He aquí otro pequeño ejercicio de práctica para seguir aprendiendo sobre este maravilloso lenguaje de programación tan popular en nuestros días. Si andas buscando un buen curso de este lenguaje conocido como Python, en lo personal te recomiendo este: Clica aquí.

And well... That's all for today! Little by little I continue advancing in my learning process and as I keep practicing, I will continue sharing content that may be useful for other students. If you are looking for a good course on this language known as Python, I personally recommend you this one: Click here


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)

H2
H3
H4
3 columns
2 columns
1 column
16 Comments