Creation and use of dictionaries

--Originally published at Programming Fundaments

A Dictionary  is a way to store data just like a list, but instead of using only numbers to get the data, you can use almost anything. This lets you treat a dictionary like it’s a database for storing and organizing data any kind of data:

>>> stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
>>> print stuff['name']
Zed
>>> print stuff['age']
39
>>> print stuff['height']
74
>>> stuff['city'] = "San Francisco"
>>> print stuff['city']
San Francisco

And that’s it. It is just really another kind of list, and a little bit simple once you get the hang of it

Examples and more at: https://learnpythonthehardway.org/book/ex39.html

 


Creation and use of ranges

--Originally published at Programming Fundaments

Range() is a function, it is used to generate a list of numbers. And it has a set of parameters:

  • start: Starting number of the sequence.
  • stop: Generate numbers up to, but not including this number.
  • step: Difference between each number in the sequence.

Some note:

  • All parameters must be integers.
  • All parameters can be positive or negative.
  • range() (and Python in general) is 0-index based, meaning list indexes start at 0, not 1. eg. The syntax to access the first element of a list is mylist[0]. Therefore the last integer generated by range() is up to, but not including, stop. For example range(0, 5) generates integers from 0 up to, but not including, 5.

Some Examples:

>>> # One parameter
>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
>>> # Two parameters
>>> for i in range(3, 6):
...     print(i)
...
3
4
5
>>> # Three parameters
>>> for i in range(4, 10, 2):
...     print(i)
...
4
6
8
>>> # Going backwards
>>> for i in range(0, 10, 2):
...     print(i)
...
0
2
4
6
8

Reading and writing of text files

--Originally published at Programming Fundaments

In Python, you don’t need to import any library to read and write files., you just eed the flie to open, and for doing so, you will have to use the “open()” command:

file_object = open(filename, mode) #where file_object is the variable to put the
file object.

There are two types of files: text and binary; A text file is often structured as a sequence of lines and a line is a sequence of characters. And a binary file is basically any file that is not a text file. Binary files can only be processed by application that know about the file’s structure.

and you have to define a mode, which the are some type of:

  • ‘r’ when the file will only be read
  • ‘w’ for only writing (an existing file with the same name will be erased)
  • ‘a’ opens the file for appending; any data written to the file is automatically added to the end.
  • ‘r+’ opens the file for both reading and writing.

At the end it will create something like this:

>>> f = open('workfile', 'w')
>>> print f

To create an text file just follow the example:

file = open("newfile.txt", "w")

file.write("hello world in the new file
")

file.write("and another line
")

file.close()

Resulting in:

$ cat newfile.txt 
hello world in the new file
and another line

Examples and More at: http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python


Validated user input

--Originally published at Programming Fundaments

In this case you wnat the user to interact with your program; for example, if they want to start making another accion by simply using the srings “yes” and “no”. Example:

endProgram = 0;
while endProgram != 1:

    #Prompt for a new transaction
    userInput = input("Would you like to start a new transaction?: ");
    userInput = userInput.lower();

    #Validate input
    while userInput in ['yes', 'no']:
        print ("Invalid input. Please try again.")
        userInput = input("Would you like to start a new transaction?: ")
        userInput = userInput.lower()

    if userInput == 'yes':
        endProgram = 0
    if userInput == 'no':
        endProgram = 1

The last program has en error, that uin every time you answer something else it will accept it and restart the program

It simply need a codeeditor to export it and that’s it

Examples & More at :http://stackoverflow.com/questions/16635073/validating-user-input-strings-in-python


Strings

--Originally published at Programming Fundaments

Strings are some of teh most popular types in python. We can create them simply by enclosing characters in quotes (Note: double quotes are treated as single quotes)

var1 = 'Hello World!'
var2 = "Python Programming"

You can also change or update these strings, to make small changes or to change it completly:

var1 = 'Hello World!'

print "Updated String :- ", var1[:6] + 'Python'

Resulting in:

Updated String :-  Hello Python

 

 


Python Lists and Tuples

--Originally published at Programming Fundaments

These are the most common build-in data type for python. These are used to store objects or values in a specific order. These are really easy to create. Here:

# Lists must be surrounded by brackets
>>> emptylst = []
# Tuples may or may not be surrounded by parenthesis
>>> emptytup = ()
Those were empty list. To create non-empty lists or tuples, the values are separated by commas:
# Lists must be surrounded by brackets
>>> lst = [1, 2, 3]
>>> lst
[1, 2, 3]
# Tuples may or may not be surrounded by parenthesis
>>> tup = 1, 2, 3
>>> tup
(1, 2, 3)
>>> tup = (‘one’, ‘two’, ‘three’)
>>> tup
(‘one’, ‘two’, ‘three’)
 (To create a tuple with only one value, add a trailing comma to the value.)
Example & More at: http://pythoncentral.io/python-lists-and-tuples/

(“Tuplas”, “TC”, 101)

--Originally published at Eduardo's Projectz

En la programación, así como en la vida real, es muy probable que se describa un objeto como un agrupamiento de datos distintos. Esto son las “Tuplas”.

Para declarar una tupla es tan simple como asignar a una variable valores encerrados en paréntesis.

a = (1, “a”, 2.5)

Un ejemplo de esto puede ser una fecha, en donde se necesitan tres elementos; día, mes y año.

Por lo que podemos decir:

captura-de-pantalla-de-2016-10-28-19-26-18

Al igual que en las listas, los datos en las tuplas tienen asignados un orden, por lo que en este caso el día de cumpleaños (2) está asignado a la posición 0; el mes (“septiembre”), a la posición 1 y el año (1998) a la posición 2.

A diferencia de las listas, las tuplas no pueden ser modificadas.

También es posible asignar muchos valores a una variable separados por comas y esto crearía una tupla.

captura-de-pantalla-de-2016-10-28-19-32-05

Para más información en este tema visita: https://www.tutorialspoint.com/python/python_tuples.htm

Para un video explicativo sobre el tema: https://youtu.be/R8mOaSIHT8U

 

 


Métodos para listas

--Originally published at Eduardo's Projectz

Dentro de las listas existen varios métodos y funciones que se utilizan para obtener un mayor beneficio de estas.

Las principales funciones son:

len()

Se utiliza para conocer la longitud total de una lista.

Para utilizarse, simplemente se escribe “len” y entre paréntesis el nombre de la lista que deseas.

captura-de-pantalla-de-2016-10-28-18-36-45captura-de-pantalla-de-2016-10-28-18-36-57

Nótese que esto te da la longitud, no la última posición que sería, en este caso, el 2.

append()

Se utiliza para añadir un valor al final de una lista, este valor tiene que ser del mismo tipo de dato que la lista.

Para utilizarse, escribe el nombre de la lista seguido por “.append” y, entre paréntesis, el valor que deseas añadir.

captura-de-pantalla-de-2016-10-28-18-38-24

captura-de-pantalla-de-2016-10-28-18-38-41

insert()

Este método permite añadir un valor a la lista en una poción determinada.

Para utilizarse, escribe el nombre de la lista seguido por “.insert” y, entre paréntesis, la posición en donde deseas poner un valor seguido de el valor, separados por una coma.

captura-de-pantalla-de-2016-10-28-18-39-41

captura-de-pantalla-de-2016-10-28-18-39-50

remove()

Esto se utiliza para quitar un valor existente en una lista.

Para utilizarse, se escribe el nombre de la lista seguido por “.remove” y el valor que se desea remover entre paréntesis.

captura-de-pantalla-de-2016-10-28-18-40-40

captura-de-pantalla-de-2016-10-28-18-40-49

index()

Esto se utiliza para conocer en que posición se encuentra un determinado valor.

Para utilizarse, se escribe el nombre de la lista seguido por “.index” y el valor que se desea conocer entre paréntesis.

captura-de-pantalla-de-2016-10-28-18-42-03

captura-de-pantalla-de-2016-10-28-18-42-13

 

images

Para más información en el tema, visita: https://docs.python.org/2/tutorial/datastructures.html

O si prefieres un video: https://youtu.be/zEyEC34MY1A

 


“Repertorios”

--Originally published at Eduardo's Projectz

En Python existe un tipo de estructura de datos llamada “lista”. Estas son secuencias mutables y vienen dotadas de una variedad de operaciones muy útiles.

Su estructura es -> a = [1,2,3]

Existen muchas funciones aṕlicables a las listas que pueden resultar muy útiles.

Las funciones básicas son: len(),  .append(),  .insert(), .remove() y .index()

A cada elemento de una lista se le asigna un orden, al primero se le asigna el numero 0; al segundo, el 1; tercero, 2; y así.

Los elementos de una lista sólo pueden ser de un mismo tipo de dato.

Ejemplo de lista

captura-de-pantalla-de-2016-10-28-18-47-25

captura-de-pantalla-de-2016-10-28-18-47-54

59943535

Para más información te recomiendo la siguiente página: http://librosweb.es/libro/algoritmos_python/capitulo_7/listas.html

Si prefieres algo más didáctico te dejo este video: https://youtu.be/vdqt8OZ-wYQ

 

 


Reto: Yo soy 196

--Originally published at Migue´s Blog

Este reto consiste en identificar los posibles numeros Lycharel, los cuales son numeros que no se convierten en palyndromos después de sumar sus inversos, para este programa considere un posible candidato aquel numero que no se volvía palindromo después de sumar 30 veces su inverso

captura-de-pantalla-de-2016-10-27-01-03-46

captura-de-pantalla-de-2016-10-27-01-04-11

captura-de-pantalla-de-2016-10-27-01-03-29

captura-de-pantalla-de-2016-10-27-01-07-11

En esta parte se declaran las variables, a continuación se introduce el inicio y el final de la serie y por ultime se añade toda la sería una variable llamada “secuencia”

captura-de-pantalla-de-2016-10-27-01-07-34

Este ciclo for es el que se va a repetir por cada numero dentro de la secuencia para ver si es número Lycharel.

Primero se invierte el número y se guarda en la variable “y” para posteriormente sumarselo

captura-de-pantalla-de-2016-10-27-01-07-52

En esta sección se analiza si es un palindromo natural, es decir sin necesidad de sumar su inverso, el if y los elif sirven para descartar los numeros del 0 al 9, debido a que ellos podrian ser tomados como palindromos pero yo no los tome debido a que solo son de 1 cifra, si aun asi es palindromo natural y tiene más de una cifra se añade uno al contador de palindromos naturales y de numeros no Lycharel y s termina el ciclo para ese numero.

captura-de-pantalla-de-2016-10-27-01-08-13

Si no es palindromo entonces se comienza a analizar sumando su inverso.

El contador se utiliza para entrar al ciclo mientras sea menor que 31, si alcanza a 31 quiere decir que ya se sumo 30 veces su inverso y no se volvio palindromo, por lo que lo consideraremos como un posible candidato.

si en una de esas sumas se vuelve palindromo se acaba el ciclo para ese numero y se añade uno al contador de numeros no Lycharel