Descargar como ppt, pdf o txt
Descargar como ppt, pdf o txt
Está en la página 1de 74

Aprendiendo a programar con Python

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

Ejemplo bajo y alto nivel


Bajo nivel (cdigo mquina x86) 8B542408 FA027706 B9010000 C84AEBF1 83FA0077 06B80000 0000C383 B8010000 00C353BB 01000000 008D0419 83FA0376 078BD98B 5BC3

Alto nivel (Python)

def fib(n): a, b = 0, 1 for i in range(n): a, b = b, a + b return a

Ejemplo bajo y alto nivel


Bajo nivel (bytecode de Python) 0 LOAD_CONST 3 PRINT_ITEM 4 PRINT_NEWLINE Alto nivel (Python) print 'Hello, world!' 1 ('Hello, world!')

Compilacin
Traduccin desde el cdigo fuente a instrucciones ejecutables

Grfico CC-SA-NC 3.0 Fuente: https://www.cs.utk.edu/~help/doku.php?id=compile:c

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.

Caracteristicas: Encapsulacin Abstraccin de datos Polimorfismo Herencia

Python: Especificacin e implementacin

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 archivo y cargarlo en array VB


Dim i, j, Array_Used As Integer Dim MyArray() As String

Dim InBuffer, Temp As String


Array_Used = 0 ReDim MyArray(50) 'open a text file here . . .

Do While Not EOF(file_no)


Line Input #file_no, MyArray(Array_Used) Array_Used = Array_Used + 1 If Array_Used = UBound(MyArray) Then

ReDim Preserve MyArray(UBound(MyArray) + 50)


End If Loop 'simple bubble sort For i = Array_Used - 1 To 0 Step -1 For j = 1 To i If MyArray(j - 1) > MyArray(j) Then 'swap

Leer archivo y cargarlo en lista Python


# Abrir un archivo de texto . . . file_object = open(FILENAME)

# Leer todas las lineas del texto en una lista (similar a un array)
lista = file_object.readlines() # Ordenar la lista

lista.sort()

Las pilas puestas


La biblioteca estndar ayuda con... Servicios del sistema, fecha y hora, subprocesos, sockets, i18n y l10n, base de datos, threads, formatos zip, bzip2, gzip, expresiones regulares, XML (DOM y SAX), Unicode, SGML, HTML, XHTML, email, manejo asincrnico de sockets, clientes HTTP, FTP, SMTP, NNTP, POP3, IMAP4, servidores HTTP, SMTP, debugger, random, curses, logging, compilador, decompilador, CSV, anlisis lexicogrfico, interfaz grfica incorporada, matemtica real y compleja, criptografa, introspeccin, unit testing, doc testing, etc., etc...

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

Prctica en intrprete interactivo >>> 2+2


4 >>> _*4 16 >>> 10/3 3 >>> float(10)/3 3.3333333333333335 >>> 10.0/3 3.3333333333333335 >>> int(2.1) 2 >>> int(2.9) 2 >>> round(2.9) 3.0 >>> int(round(2.9)) 3 >>> round(2.932224,2) 2.9300000000000002 >>> print round(2.932224,2) 2.93

Prctica en intrprete interactivo II


>>> "hola" + " mundo!" 'hola mundo!' >>> ("hola" + " mundo!").upper() 'HOLA MUNDO!' >>> ' 123'.strip() '123' >>> 123.strip() File "<stdin>", line 1 123.strip() ^ SyntaxError: invalid syntax >>> >>> str(123) '123' >>> int('123') 123

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".

Tipo de datos: Primarios y derivados

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 informacin: http://docs.python.org/library/decimal.html

str (String o Cadenas)


>>> 'Hola mundo!' 'Hola mundo!' >>> a='Hola mundo!' >>> len(a) 11 >>> a.lower() 'hola mundo!' >>> a.count('o') 2 >>> a.find('H') 0 >>> a.find('mundo') 5 >>> a.find('e') -1 >>> a.index(' ') 4 >>> a.index('e') Traceback (most recent call last): File "<pyshell#52>", line 1, in <module> a.index('e') ValueError: substring not found >>> a.split(' ') ['Hola', 'mundo!'] http://docs.python.org/library/string.html

Datos ordenados: Listas


>>> >>> >>> [1, >>> 5 >>> [1, >>> [1, >>> [1, >>> >>> [1, >>> >>> [1, >>> 1 >>> 4 >>> [4, >>> 5 mi_lista = [1,2,3] mi_lista.append(5) mi_lista 2, 3, 5] mi_lista.pop() mi_lista 2, 3] mi_lista + [4] 2, 3, 4] mi_lista 2, 3] mi_lista = mi_lista + [4] mi_lista 2, 3, 4] mi_lista.extend([5,6]) mi_lista 2, 3, 4, 5, 6] mi_lista[0] mi_lista[3] mi_lista[3:5] 5] mi_lista[-2]

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]]

Tuplas: Similares a listas, aunque inmutables.


>>> t1 = ('sgn1545',5,45) >>> t1[0] 'sgn1545' >>> 5 in t1 True >>> t1.index(45) 2 >>> t1.count(45) 1 >>> t1.append(4) Traceback (most recent call last): File "<pyshell#39>", line 1, in <module> t1.append(4) AttributeError: 'tuple' object has no attribute 'append' >>> t1.pop() Traceback (most recent call last): File "<pyshell#40>", line 1, in <module> t1.pop() AttributeError: 'tuple' object has no attribute 'pop' >>> t1.remove(45) Traceback (most recent call last): File "<pyshell#44>", line 1, in <module> t1.remove(45) AttributeError: 'tuple' object has no attribute 'remove'

Diccionarios: Datos agrupados por clave-valor, sin orden.


>>> en2es = {'blue':'azul','red':'rojo','black':'negro'} >>> en2es['blue'] 'azul' >>> en2es['azul'] Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> en2es['azul'] KeyError: 'azul' >>> 'blue' in en2es #verifico que una clave exista en 1 dict. True >>> en2es.keys() ['blue', 'black', 'red'] >>> en2es.values() ['azul', 'negro', 'rojo'] >>> en2es.items() [('blue', 'azul'), ('black', 'negro'), ('red', 'rojo')] >>> en2es.get('green','N/D') 'N/D' >>> es2en = {} #Diccionario vacio >>> es2en['azul'] = 'blue' #Cargo un par clave-valor >>> es2en {'azul': 'blue'}

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'])

Conversin de datos: En Python siempre es explicito

>>> 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

Python 3: input() es raw_input() Salida: print Python 3: print()

Estructuras de control de flujo

if: Condicin for: Repeticin while: Repeticin

if
if <expresion1>: <Instrucciones> elif <expresion2>: <Instrucciones> else: <Instrucciones>

if coord != 'N/A': year = int(coord[0][-4:])

for
for <var> in <iterable>: <instrucciones>

for x in [1, 3, 4]: print x

while

while <expresion>: <instrucciones> while mi_set: print mi_set.pop()

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()

Apertura secuencial de un archivo

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

with open('archivo.txt') as fh: for line in fh: print line

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:

fh = open('/home/yo/archivo.txt','w') fh.write('1\n2\n3\n4\n5\n') fh.close()

Archivos CSV (Comma separated file)

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 CSV sin usar mdulo CSV:


fh = open('archivo.txt') for line in fh: linea = line.split(',') # procesar elementos: nombre = linea[0] apellido = linea[1] # etc, etc fh.close()

CSV con mdulo CSV


import csv lineas = csv.reader(open('fn.csv')) for line in lineas: nombre = line[0] apellido = line[1]

Cambiando separador (delimitador):


lineas = csv.reader(open('fn.csv'),delimiter=';')

Dialectos: >>> csv.list_dialects() ['excel-tab', 'excel']

Escribiendo archivos CSV


>>> >>> ... >>> >>> import csv spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamWriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

Lectura y escritura de Excel: xlrd y xlwt


Instalando Easy_install: En Windows: http://pypi.python.org/pypi/setuptools

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)

Creando planillas Excel:


import xlwt list1 = [1,2,3,4,5] list2 = [234,267,281,301,331] wb = xlwt.Workbook() ws = wb.add_sheet('Primera hoja') ws.write(0,0,'Column A') ws.write(0,1,'Column B') i = 1 for x,y in zip(list1,list2): #Walk 2 list @ once. ws.write(i,0,x) # Fila, Columna, Datos. ws.write(i,1,y) i += 1 wb.save('mynewfile.xls')

Pickle: Persistencia simple de datos.


Pickle vs. cPickle Grabar:

>>> spdict = {'blue':'azul','red':'rojo'} >>> spdict {'blue': 'azul', 'red': 'rojo'} >>> import cPickle >>> fh = open('spict.data','w') >>> cPickle.dump(spdict, fh) >>> fh.close()
Leer:

>>> spdict = cPickle.load(open('spict.data')) >>> spdict {'blue': 'azul', 'red': 'rojo'}

Modularizando el cdigo Ejemplo de funcin:


Parmetros fijos:

>>> len('Hola') 4
Parmetros variables:

>>> [0, >>> [2, >>> [2,

range(5) 1, 2, 3, 4] range(2,5) 3, 4] range(2,5,2) 4]

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

Funcin que no devuelve nada (devuelve None)


def savelist(L, fn): ''' 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

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

Nmero indeterminado de argumentos


No se conoce de antemano cuantos argumentos irn en la funcin. El argumento que tenga el * (asterisco) ser pasado como una tupla.

def promedio(*numeros): if len(numeros)==0: return None else: return(float(sum(numeros))/len(numeros))

Nmero indeterminado de argumentos con claves


Los argumentos en exceso son pasados como diccionario

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

rpm, apt-get, etc

(3) Easy Install (easy_install) $ sudo apt-get install python-setuptools $ sudo easy_install NOMBRE_DEL_MODULO

Modulos como programas:


if __name__ == "__main__": # hacer algo

Biblioteca estndar (PSL): http://docs.python.org/library/


import os # 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 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()

import zipfile myfile = zipfile.ZipFile('archivo.zip')

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

Mailing list: http://python.org.ar/pyar/ListaDeCorreo List para incio: http://groups.google.com/group/a-python

Mas recursos: http://python.org.ar/pyar/AprendiendoPython

También podría gustarte