Leer y escribir documentos en Python

--Originally published at Migue´s Blog

En Python puedes abrir un doxumento para utilizar o leer los datos que se encuentran en él.

Para abrir un documento se hace de la siguiente manera.

captura-de-pantalla-de-2016-11-24-00-42-17

primero se escribe la variable en donde se guardará, después el signo igual, seguido de la función open, la función open utiliza 2 argumentos, el primero la ubicación del archivo, si el archivo se encuentra en la misma carpeta que el programa solo se necesita escribir el nombre del archivo, el seguno argumento es el modo, existen 4 modos.

“r”  Solo para leer datos.

“w”  Solo para escribir datos.

“a”  Para agregar datos al final del archivo

“r+”  Para leer y escribir datos.

Para crear un documento se escribe la variable, seguido de open, el nombre que le asignaremos al documento y con el modo “w” para poder escribir en el.

Para escribir en el utilizamos write.

captura-de-pantalla-de-2016-11-24-00-49-01


Validación de la entrada del Usuario.

--Originally published at Migue´s Blog

Cuando requerimos que el usuario introduzca datos es muy importante que nos aseguremos que el usuario esta introduciendo datos que el programa pueda utilizar, o datos que nostros ocupemos, debido a que si el usuario introduce otro tipo de datos nuestro programa puede fallar y crashear.

captura-de-pantalla-de-2016-11-24-00-24-34

captura-de-pantalla-de-2016-11-24-00-25-28

Para evitar esto podemos utilizar un ciclo, el cual regrese al usuario a introducir los datos hasta que ingrese un resultado válido.

captura-de-pantalla-de-2016-11-24-00-32-24captura-de-pantalla-de-2016-11-24-00-32-07

Utilizamos el ciclo while para que se mantenga pidiendo información hasta que se rompa el ciclo.

con la Función “try” pedimos los datos, con  la función “except” analizamos si los datos solicitados son un error, de ser así se ejecuta su bloque de innstrucciones y con la función “else” se rompe el ciclo cuando se da un valor adecuado.

 


Creación de listas y Tuplas en python

--Originally published at Migue´s Blog

Las listas y Tuplas se utilizan par almacenar datos, los cuales posteriormente podemos utilizarlos, buscarlos, realizar operaciones con ellos, concatenarlos, ordenarlos, etc.

La diferencia entre una tupla y una lista es que la lista es variable, es decir durante la ejecución del programa podemos agregarle elementos con la funcion “append”, o eliminar elementos con la función “del”.

En las tuplas no se puede hacer esto, son inmutables, es decir, se quedan con los mismos valores con los que iniciaron el programa.

Para las listas se utilizan corchetes, para las tuplas parentesis.

captura-de-pantalla-de-2016-11-24-00-11-26captura-de-pantalla-de-2016-11-24-00-12-07


Uso de else y elif en python

--Originally published at Migue´s Blog

Cuando utilizamos el condicional “if”, no siempre se cumple la condición, también hay posibilidades de que la condición sea falsa, para estos casos utilizamos los condicionales “elif” y “else”.

Elif

Elif se utiliza para cuando puede haber más de una opción, y no solamente 2 (verdadero o falso), funciona igual que el “if”, solamente se entra al ciclo si se cumple la condición descrita en el, la diferencia es que solo se analiza si el “if”, y los “elif” anteriores a él son falsos, si uno es verdadero no se analiza el “elif”

captura-de-pantalla-de-2016-11-23-23-31-57captura-de-pantalla-de-2016-11-23-23-32-28

Else

Else funciona igual, la diferencia es que en el else ya no se escriben argumentos, y se analiza solamente si el “if” y los “elif” anteriores a él son falsos.

captura-de-pantalla-de-2016-11-23-23-34-26captura-de-pantalla-de-2016-11-23-23-34-42


¿Cuándo usar cada tipo de ciclo?

--Originally published at Migue´s Blog

Existen 3 tipos de condicionales.

If:

El ciclo If se utiliza para que se ejecute un grupo de ordenes 1 sola vez y solamente si se cumple la condición que marca el “If”, si es falso se salta ese bloque de comandos.

Para utilizaro se escribe “if”, seguido de la condición que se debe de cumplir, se termina la condición con 2 puntos “:” y después se escribe el bloque de instrucciones cada instrucción con una sangría, cuando se quita la sangría se acaba el bloque de instrucciones del “If”.

captura-de-pantalla-de-2016-11-23-23-07-14

while:

Funciona de una manera similar al “if”, solo se ejecuta su bloque de instrucciones si se cumple la condición establecida, la diferencia es que este ciclo se sigue repitiendo mientras la condición se siga repitiendo, para salir la condición debe de ser falsa, por lo que si no tienes cuidado puedes crear un ciclo infinito.

Para usarlo se escribe “while”, seguido de la condición, terminas la condición con dos puntos “:” y su bloque de instrucciones se escribe con sangría.

captura-de-pantalla-de-2016-11-23-23-11-08

For:

Este ciclo no usa una condición para entrar en el, siempre se ejecuta, pero este ciclo se ejecuta un determinado numero de veces, puede ser por un número ya definido, una variable con  valor númerico ya definido, por el número de elementos en una lista o el número de carácteres en un string.

Cada vez que se entra al ciclo una variable cambia de valor, normalmente se utiliza la variable “i”, esta variable adquiere un nuevo valor dependiendo del argumento, por ejemplo si utilizamos la string “Hello”, se entrará al ciclo 5 veces.

1.- i=H          2.-i=e       3.-i=l      4.-i=l        5.-i=o

Para utilizarlo se escribe “for” seguido de la variable a utilizar, después se escribe “in” seguido del argumento a analizar, se termina con dos

captura-de-pantalla-de-2016-11-23-23-17-42
captura-de-pantalla-de-2016-11-23-23-19-02
Continue reading "¿Cuándo usar cada tipo de ciclo?"

Nesting of conditional statements

--Originally published at Luis Santana's Blog

This is me right now hehe. giphy

Now, talking about Python and programming. There will be times where you may want to check a condition after another condition solves for true, this means that inside an “if” condition you can have another “if” condition and several “elif” conditions too. You can use this tool to make your code easier to understand and help you finish earlier.

Here you can see an example:

nesting

You can check this link I used to get my information:

https://www.tutorialspoint.com/python/nested_if_statements_in_python.htm


Creation of sytrings and how to use them

--Originally published at Luis Santana's Blog

This blog is really special to me, and I would like to take a minute to explain it why. This post means that I’m half way there and just missing four posts.

2002

In this post I will talk about strings and how to create them. In order to create a string you should enclose your text in quotes, (it is the same if you use single quotes or double quotes). You can see an example below:

string

Check this link if you want to learn more about strings: https://www.tutorialspoint.com/python/python_strings.htm

 


Zen of Python

--Originally published at Python

2zen

I’ve been looking more into the Zen of Python and what it actually says. First I disregarded it because I knew most of the things it talks about, but the I thought “What about people who are just starting?” Of course they won’t know how to guide themselves through the world of programming. So I decided to talk about the points that I believe are the most important in the Zen of Python.

The first one being “simple is better than complex”. It is important to understand this point because there are times when people try to do a super complex programs when in reality, it can be simplified into something everyone can understand. Making something complex will only bring you trouble in the future. If something goes wrong, then you will have to go through your complex program, understand the problem, why it is there, and then come up with a solution. Keeping things simple makes your life way easier.

Next is “Readability counts”. It is important that your code is readable. This point is similar to the last one, but a little more general. You want your code to be readable so that you can understand it, as well as others. If it is hard to understand, then you won’t be able to figure out your problem as easy as you could if it was. Also, if you ever show this code to others, they will be just as confused as you because they won’t understand anything.

Finally, I just want to talk about the point stating “Now is better than never.” Everyone that is starting to program has to take this one into account. Leaving everything for later won’t help you at all. If you want to be good at programming, you need to start

Continue reading "Zen of Python"

Use of recursion for repetitive algorithms

--Originally published at Luis Santana's Blog

Continuing this long marathon of posts, next topic will be use of recursion for repetitive algorithms. 

According to Lepe in 2015, he says (and I completely agree, there’s wisdom in his words). “Recursion is a way of programming in wich you use the same function in a function”. That means it calls itself one or more times in its body. Usually, it is returning the return value of this function call. If a function definition fulfils the condition of recursion, we call this function a recursive function.

200
Here’s the link

 

Here’s a good example, actually the best example I could find:

factorial


“For” loops

--Originally published at Luis Santana's Blog

What’s up lads! It’s been a while since my last post but that will change during this day, because I’ll do in a single day all the posts I didn’t finish in this partial hehe so brace yourselves.

 

635656667301311336741304865_resized_winter-is-coming-meme-generator-brace-yourselves-finals-are-coming-45e03b
Here’s the link

 

So, this post is dedicated to “for” loops, this loop is an iterator based for loop. It steps through the items of lists, tuples, strings, the keys of dictionaries and other iterables. The Python for loop starts with the keyword “for” followed by an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through.

Here’s an example of “for” loops:

for

In this example the “for” loops work fine because you know exactly the amount of teams you have and won’t repeat infinitely.

You can check this link with examples, it helped me a lot