Python en 8 Horas
Python en 8 Horas
Curso en 8 horas
Qu es un programa?
Un programa es un conjunto de instrucciones diseadas para ordenar a la computadora a hacer algo.
Es similar a una receta de cocina, que consiste en una lista de ingredientes e instrucciones paso a paso donde se usan dichos ingredientes.
Receta
Tomates fritos.
Ingredientes:
1 Tomate 200 gr Queso 1 huevo 100 gr Pan rallado Aceite
Instrucciones:
Cortar el tomate en 2 rodajas. Poner queso entre las rodajas, mezclar con huevo, cubrir con pan rallado y freir en aceite hasta que se dore.
Primer programa
Cdigo
seq1 = 'Hola' seq2 = ' mundo!' total = seq1 + seq2 print total
Resultado
Hola mundo!
Niveles de abstraccin
Compilacin
Traduccin desde el cdigo fuente a instrucciones ejecutables
Consecuencias de la compilacin
Tiempo de compilacin Aceleracin en la ejecucin del software Software dependiente de una plataforma
Paradigmas de programacin
Procedural / Estructurada: C, Pascal, Perl. Orientada a Objetos: C++, Java. Lgico: Prolog, Lisp.
Programacin procedural
Los programas tienen rutinas o funciones con los pasos a seguir. Beneficios: Estructurar el cdigo en bloques para reutilizarlos. Seguimiento de la lgica del programa (sin saltos a posiciones arbitrarias, aka go to).
POO (OOP)
Se usan objetos para disear los programas. Los objetos son estructuras de datos que tienen propiedades (caracteristicas) y mtodos (acciones) que le son propios.
Especificacin: Definicin de caracteristicas del lenguaje Implementacin: Programa que cumple con dicha especificacin. Ej.: CPython, IronPython, Jython
Caractersticas de Python
Fcil de aprender y de programar Fcil de leer (similar a pseudocdigo) Interpretado (Rpido para programar) Datos de alto nivel (listas, diccionarios, sets, etc) Libre y gratuito Multiplataforma (Win, Linux y Mac) Pilas incluidas Cantidad de bibliotecas con funciones extras Comunidad
# Leer todas las lineas del texto en una lista (similar a un array)
lista = file_object.readlines() # Ordenar la lista
lista.sort()
Bibliotecas externas
Bases de datos
MySQL, PostgresSQL, MS SQL, Informix, DB/2, SQLite Qt, GTK, win32, wxWidgets, Cairo Django, Turbogears, Zope, Plone, webpy
Interfaces grficas
Frameworks Web
Y un montn ms de temas...
Biopython: Manejo de secuencias genticas PIL: para trabajar con imgenes
Mas pilas...
Bases de datos
MySQL, PostgresSQL, MS SQL, Informix, DB/2, SQLite Qt, GTK, win32, wxWidgets, Cairo Django, Turbogears, Zope, Plone, webpy
Interfaces grficas
Frameworks Web
Y un montn ms de temas...
Biopython: Manejo de secuencias genticas PIL: para trabajar con imgenes
CPython e IDLE
Help incorporado
>>> help()
Welcome to Python 2.6! This is the online help utility.
If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://docs.python.org/tutorial/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam".
Primarios (o primitivos): No necesitan de otro tipo de datos, como numericos (int, float, decimal, complex) y str (cadenas). Derivados: Agrupan a alguno de los anteriores, como listas, diccionarios, tuplas, etc. Se pueden subclasificar segn distintos parmetros: Ordenados (o secuenciales) Desordenados Mutables Inmutables
>>> type(5) <type 'int'> >>> type(5.0) <type 'float'> >>> type(5 + 5.0) <type 'float'> >>> 5 + 5.0 10.0 >>> type(2+3j) <type 'complex'> >>> (2+3j).real 2.0 >>> (2+3j).imag 3.0 >>> type('Hola!') <type 'str'> >>> 'hola' + ' mundo!' 'hola mundo!' >>> 'hela' + 2 Traceback (most recent call last): File "<pyshell#32>", line 1, in <module> 'hela' + 2 TypeError: cannot concatenate 'str' and 'int' objects >>> 'hela' + str(2) 'hela2'
Decimal El problema de los nmeros flotantes: >>> 0.1 + 0.1 + 0.1 - 0.3 5.5511151231257827e-17 Una manera de evitar esto: >>> round(0.1 + 0.1 + 0.1 - 0.3,1) 0.0 Alternativamente, para no perder precisin:
>>> from decimal import Decimal >>> Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3') Decimal('0.0')
Mas sobre listas: >>> variada = ['boga', 'cornalito', 'tararira'] >>> variada[2] 'tararira' >>> variada[2][2:8] 'rarira' >>> variada[2][2:] 'rarira' >>> variada.append('pulpo') >>> variada ['boga', 'cornalito', 'tararira', 'pulpo'] >>> variada.remove('cornalito') >>> variada ['boga', 'tararira', 'pulpo'] >>> variada.sort() >>> variada ['boga', 'pulpo', 'tararira'] >>> variada.index('pulpo') 1 >>> variada.index('pulpa') Traceback (most recent call last): File "<pyshell#33>", line 1, in <module> variada.index('pulpa') ValueError: list.index(x): x not in list >>> 'pulpo' in variada True >>> 'pulpa' in variada False
List comprehesion
>>> vec = [2, 4, 6] >>> [3*x for x in vec] [6, 12, 18] >>> [3*x for x in vec if x > 3] [12, 18] >>> [3*x for x in vec if x < 2] [] >>> [[x,x**2] for x in vec] [[2, 4], [4, 16], [6, 36]]
Ejemplo de diccionario
tom_map = { 1992: { 1:[ ('1A', 8.9), ('1B', 13.6), ('1C', 22.3), ('1D', 60.8), ('1E', 70.4), ('1F-G', 93.6), ('1H', 111.7), ('1I', 129.2), ('1J', 10000)], 2:[ ('2A', 1.6), ('2B', 16.2), ('2C', 18.6), ('2D', 22.5), ('2E', 27.6), ('2F', 44.8), ('2G', 68), ('2H', 72.4), ('2I', 76.1), ('2J', 100.5), ('2K', 122.9), ('2L', 10000)], 3:[ ('3A', 24.2), ('3B', 30.4), ('3C', 54.8), ('3D', 61.1), ('3E', 64.4), ('3F', 97), ('3G', 98.4), ('3H', 108), ('3I', 100000)], 4:[ ('4A', 2), ('4B', 6.6), ('4C', 32.9), ('4D', 38), ('4E', 50), ('4F', 58.4), ('4G', 100.5), ('4H', 113.2), ('4I', 10000)], 5:[ ('5A', 4.6), ('5B', 17.2), ('5C', 42.8), ('5D', 44.6), ('5E', 72.7), ('5F', 75), ('5G', 84.9), ('5H', 92.3), ('5I', 10000)], 6:[ ('6A', 25), ('6B', 31.8), ('6C', 42), ('6D', 61.9), ('6E', 69.6), ('6F', 89.6), ('6G', 10000)], 7:[ ('7A', 3), ('7B', 11), ('7C', 21), ('7D', 36.8), ('7E', 52.6), ('7F', 70.6), ('7G', 75.7), ('7H', 10000)], 8:[ ('8A-B', 18.2), ('8C', 20.1), ('8D', 41.1), ('8E', 61.3), ('8F', 80.6), ('8G', 89.1), ('8H', 10000)], 9:[ ('9A', 8.9), ('9B', 22), ('9C', 28.9), ('9D', 39), ('9E', 56.4), ('9F', 57.4), ('9G', 64.2), ('9H', 69.1), ('9I', 79), ('9J', 102.6), ('9K', 10000)], 10:[ ('10A', 12), ('10B', 37.3), ('10C-D', 48.8), ('10E', 64.6), ('10F', 84.1), ('10G', 10000)], 11:[ ('11A', 20.8), ('11B', 32.3), ('11C', 45.4), ('11D', 59.3), ('11E', 79.9), ('11F', 83.3), ('11G', 83.8), ('11H', 10000)], 12:[ ('12A', 13.8), ('12B', 28.2), ('12C', 32.5), ('12D', 41), ('12E', 47.6), ('12F', 67.3), ('12G', 86), ('12H', 91.8), ('12I', 10000)]} , 2000 :{1:[ ('1A', 19.5), ('1B', 25), ('1C', 31.8), ('1D', 70), ('1E', 92.7), ('1F-G', 127.6), ('1H', 142), ('1I', 163), ('1J', 10000)], 2:[ ('2A', 4), ('2B', 13), ('2C', 16), ('2D-E', 31), ('2F', 45.1), ('2G', 81.2), ('2H', 85), ('2I', 90.1), ('2J', 116.1), ('2K', 143), ('2L', 10000)], 3:[ ('3A', 32), ('3B', 33), ('3C', 71.5), ('3D', 83), ('3E', 85), ('3F', 129), ('3G', 140), ('3H-I', 10000)], 4:[ ('4A-B', 12), ('4C', 46), ('4D', 56), ('4E', 72.5), ('4F', 75), ('4G', 101), ('4H', 124), ('4I', 10000)], 5:[ ('5A', 13.5), ('5B', 30), ('5C', 69), ('5D', 71.1), ('5E', 102), ('5F', 104), ('5G', 110.1), ('5H', 112), ('5I', 10000)], 6:[ ('6A', 33.5), ('6B', 38.6), ('6C', 50), ('6D', 71), ('6E', 81), ('6F', 96), ('6G', 10000)], 7:[ ('7A', 2), ('7B', 7), ('7C', 21.5), ('7D', 45.5), ('7E', 48), ('7F', 72.3), ('7G', 73), ('7H', 10000)], 8:[ ('8A', 2), ('8B', 23.8), ('8C', 30), ('8D', 40), ('8E', 57), ('8F', 68.3), ('8G', 84), ('8H', 10000)], 9:[ ('9A', 4), ('9B', 28), ('9C', 32), ('9D', 35), ('9E', 50.3), ('9F', 53.7), ('9G', 57.5), ('9H', 62), ('9I', 72.5), ('9J', 102), ('9K', 10000)], 10:[ ('10A', 11), ('10B', 43), ('10C-E', 61.5), ('10F', 80), ('10G', 10000)], 11:[ ('11A', 20.5), ('11B', 36.5), ('11C', 49), ('11D', 76), ('11E', 90), ('11F-G', 92), ('11H', 10000)], 12:[ ('12A', 21), ('12B', 32.5), ('12C', 38), ('12D', 55.3), ('12E', 68.5), ('12F-G', 114), ('12H', 117), ('12I', 10000)]}}
Sets (Conjuntos)
>>> mi_set = set() >>> mi_set.add('jose') >>> mi_set.add('juan') >>> mi_set.add('natalia') >>> mi_set.add('viki') >>> mi_set set(['jose', 'juan', 'viki', 'natalia']) >>> mi_set.pop() 'jose' >>> mi_set set(['juan', 'viki', 'natalia']) >>> mi_set.add('jose') >>> mi_set set(['jose', 'juan', 'viki', 'natalia']) >>> mi_set.add('jose') >>> mi_set set(['jose', 'juan', 'viki', 'natalia']) >>> otro_set = set(['juan','karina','diana']) >>> otro_set set(['diana', 'juan', 'karina']) >>> mi_set.intersection(otro_set) set(['juan']) >>> mi_set.union(otro_set) set(['jose', 'viki', 'natalia', 'diana', 'juan', 'karina']) >>> mi_set.difference(otro_set) set(['jose', 'viki', 'natalia'])
>>> rgb=dict([('blue','#0000FF'),('black','#000000'),('red','#FF0000')]) >>> rgb['black'] '#000000' >>> list(t1) ['sgn1545', 5, 45] >>> lista = list('Hago 1 lista') >>> lista ['H', 'a', 'g', 'o', ' ', '1', ' ', 'l', 'i', 's', 't', 'a'] >>> tuple(lista) ('H', 'a', 'g', 'o', ' ', '1', ' ', 'l', 'i', 's', 't', 'a') >>> str(lista) "['H', 'a', 'g', 'o', ' ', '1', ' ', 'l', 'i', 's', 't', 'a']" >>> ''.join(lista) 'Hago una lista' >>> 'Hago una lista'.split(' ') ['Hago', 'una', 'lista']
Data I/O
Entrada: input('prompt') raw_input('prompt') >>> edad = Ingrese la >>> edad 33 >>> edad = Ingrese la >>> edad '33' input('Ingrese la edad: ') edad: 33 raw_input('Ingrese la edad: ') edad: 33
if
if <expresion1>: <Instrucciones> elif <expresion2>: <Instrucciones> else: <Instrucciones>
for
for <var> in <iterable>: <instrucciones>
while
Ejercicios
Archivos
Lectura: (1) Abrir (open) (2) Leer (read, readlines, readline) (3) Cerrar (close) Escritura: (1) Abrir (open) (2) Guardar (write) (3) Cerrar (close)
Leyendo un archivo: (1) La funcin open crea un filehandle. open(filename[, mode[, bufsize]]) Ej: fh = open('mi_archivo.txt','r')
(2) read(n): Lee n bytes, por defecto lee el archivo entero. readline(): Devuelve str con una sola linea readlines(): Devuelve una lista con str por cada lnea
fh = open('archivo.txt') contenido = fh.read() print contenido fh = open('archivo.txt') contenido = fh.readlines() print contenido contenido = '' fh = open('archivo.txt') while True: line = fh.readline() contenido += line if line='' break print contenido # Para todos: fh.close()
fh = open('archivo.txt')
contenido = '' for line in fh: contenido += line fh.close()
Leyendo con 'with' (Python 2.6 en adelante) with EXPRESION as VARIABLE: BLOQUE DE CODIGO
Escribiendo archivos
Modos de escritura:
w: Write, graba un archivo nuevo, si existe, borrarlo.
a: Append (agregar), agrega informacin al final de un archivo preexistente. Si no existe, crea uno nuevo (uso tpico: logs).
Ejemplo:
Ejemplo:
Sebastin,Perez,33,23566777 Jose,Martinez,23,42121329 Karina,Gonzalez,32,24159857 Maria Laura,Yaes,19,43852144 Otro separador: Sebastin;Perez;33;23566777 Jose;Martinez;23;42121329 Karina;Gonzalez;32;24159857 Maria Laura;Yaes;19;43852144
Leyendo Excel:
import xlrd iedb = {} # Empty dictionary book = xlrd.open_workbook('sampledata.xls') sh = book.sheet_by_index(0) for i in range(1,sh.nrows): #skips fist line. iedb[sh.cell_value(rowx=i, colx=1)] = \ sh.cell_value(rowx=i, colx=2)
>>> spdict = {'blue':'azul','red':'rojo'} >>> spdict {'blue': 'azul', 'red': 'rojo'} >>> import cPickle >>> fh = open('spict.data','w') >>> cPickle.dump(spdict, fh) >>> fh.close()
Leer:
>>> len('Hola') 4
Parmetros variables:
Definicin de funcin:
def Nombre_Funcion(parametro1, parametro2, etc): ''' Descripcion optativa ''' cdigo de la funcin return DATA
Ejemplo:
def tair_data(f_in): tair9_d = {} for rec in SeqIO.parse(open(f_in),'fasta'): tair9_d[rec.id] = rec.description return tair9_d
Importante: Ambito de variables
Mas ejemplos:
def sgn_u(bacsgn,rango_ini,rango_end,sgn_u_tomato_d): """ Procesa un nombre tipo 'C02HBa0106H06.1' con sus posiciones, compara con datos en sgn_u_tomato_d y retorna cuales son. """ sgn_u = [] if bacsgn in sgn_u_tomato_d: for gendata in sgn_u_tomato_d[bacsgn]: if gendata[0] <= rango_ini <= rango_end <= gendata[1]: sgn_u.append(sgns.get(gendata[2],gendata[2])) return sgn_u def august(name,rango_ini,rango_end,crms_d): """ Procesa un nombre tipo 'C02HBa0106H06.1' con sus posiciones, compara con datos en crms_d y dice si es AUGUST + o -. """ if name in crms_d: for x in crms_d[name]: if x[0] <= rango_ini <= rango_end <= x[1]: return True return False
Parametros por defecto def savelist(L, fn='tmp.txt'): ''' Una lista (L) es grabada como archivo con nombre fn ''' fh = open(fn,'w') for x in L: fh.write(x+'\n') fh.close() return None
def cli(nombre,**parametros): linea = '' for p_key,p_vals in parametros.iteritems(): linea += ' -' + p_key + ' ' + p_vals return nombre+linea
Mdulos
Los mdulos son archivos con instrucciones (funciones, clases) y datos para ser usado desde un programa.
Usando mdulos
>>> import os >>> os.getcwd() '/home/sbassi' >>> from os import getcwd >>> getcwd() '/home/sbassi' >>> from os import * >>> getcwd() '/home/sbassi' >>> sep '/' >>> import xml.etree.ElementTree as ET
Instalando mdulos
(1) Copiar al PYTHONPATH
>>> import sys >>> sys.path ['', '/usr/local/lib/python2.6/dist-packages/xlrd0.7.1-py2.6.egg', '/usr/local/lib/python2.6/distpackages/biopython-1.52-py2.6-linux-i686.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/platlinux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/libdynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/Numeric', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/usr/lib/python2.6/dist-packages/wx-2.6-gtk2unicode', '/usr/local/lib/python2.6/dist-packages']
Instalando mdulos
(2) Usar gestor de paquetes
(3) Easy Install (easy_install) $ sudo apt-get install python-setuptools $ sudo easy_install NOMBRE_DEL_MODULO
import glob
# directorio actual? print os.getcwd() # listo todos los archivos del dir actual ma = os.listdir(os.getcwd()) # necesito solo los terminados en .txt ma2 = [] for x in ma: if x.endswith('.txt'): ma2.append(x) print ma2 # otra manera de retener los terminados en .txt ma2 = [x for x in ma if x.endswith('.txt')] print ma2
import zipfile a_list = ["Test1.txt", "Test2.txt", "Test3.txt"] # Guardar archivos en un zip zfilename = "mi_archivozipeado.zip" zout = zipfile.ZipFile(zfilename, "w") for fname in a_list: zout.write(fname) zout.close()
if myfile.is_zipfile(archivo.zip): print "Es un archivo zip OK" for fn in myfile.namelist(): print fn myfile.extractall() else: print "No es un archivo zip valido"
>>> import time >>> # esperar n segundos. >>> time.sleep(2) >>> time.asctime() 'Tue Dec 1 20:07:34 2009' >>> time.time() 1259708878.824398 >>> time.time() 1259708882.5425911 >>> a = time.time() >>> b = time.time() >>> b-a 6.0693800449371338
Para medir tiempo de procesos, usar mdulo timeit
import sys from optparse import OptionParser usage = "usage: %prog [password_file] [dictionary_file]\n" usage += "or %prog [options] [password_file]\n\n" usage += "Type %prog -h for more information" parser = OptionParser(usage, version="%prog 1.0") parser.add_option("-i", "--input", dest="input_file", help="Input file. ") parser.add_option("-d", "--dictionary", dest="dict_file", help="Use a dictionary file. ") (opts, args) = parser.parse_args() if opts.input_file: fh = open(opts.input_file) elif args: fh = open(args[0]) elif sys.stdin: fh = sys.stdin else: parser.error("Enter an input file") if len(args)==2: fd = open(args[1]) elif opts.dict_file: fd = open(opts.dict_file) else: parser.error('Enter a dictionary file or aspell dictionary')
Subprocess
import subprocess
cmd = ['ps', '-eo', 'pcpu'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) std = p.communicate()[0] allstatus = str(std).split('\n')
webbrowser
>>> import webbrowser >>> webbrowser.open('http://www.py4bio.com') True >>> b = webbrowser.get('opera') >>> url = 'http://www.py4bio.com' >>> b.open(url) True
Mas ayuda...
Manual de Python: http://pyspanishdoc.sourceforge.net/tut/tut.html